Node JS Create Publish And Use Custom Package Module Example

This example will tell you how to create a custom Node JS module, how to publish it to the NPM central repository, and how to import it as a library into your node application to use.

1. How To Create Custom Node JS Package Module.

  1. This custom node js module contains five files, they are package.json, README.md, user_account.js, user_account.txt, and jerry-zhao-user_account-1.0.0.tgz.
    C:\WORKSPACE\WORK\DEV2QA.COM-EXAMPLE-CODE\JAVASCRIPTEXAMPLEWORKSPACE\NODEJSWORKSPACE\CREATEPUBLISHUSECUSTOMMODULE
    │   test_user_account_module.js
    │   user_account.txt
    │
    └───node_modules
        └───user_account
                jerry-zhao-user_account-1.0.0.tgz
                package.json
                README.md
                user_account.js
                user_account.txt
  2. Create a node js project and custom module directory CreatePublishUseCustomModule/node_modules/user_account. The custom module name is @jerry-zhao/user_account, this module provides a user account register and login function.
  3. Then open a terminal and go to the above folder and execute the command npm init in the command line. This command will guide you to create the module. You can refer to How To Create Custom NPM Modules to learn more.
  4. After the above process, a package.json file will be created. Below is the content of this file. You can create a git hub account and a repository to save your node js project source files, and add some keywords for users to search this custom node js module.
    {
      "name": "@jerry-zhao/user_account",
      "version": "1.0.0",
      "description": "Provide user account login and regist function.",
      "main": "user_account.js",
      "repository" :{
        "type" : "git",
        "url" : "https://github.com/happyzhaosong/Custom-Node-JS-Example"
      },
      "keywords": [
        "user account",
        "register",
        "login"
      ],
      "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1"
      },
      "author": "jerry",
      "license": "ISC"
    }
  5. You can also create a README.md file which will contain the description of this custom module as below.
    This is a custom node js module which provide user account register and login features.
    
    The account info will be saved in a text file, the file name is user_account.txt.
    
    One line text in above file represent an account, the line data format is userName = password.
  6. Now create the js file user_account.js and input the below contents in it.
    // Import fs module.
    var fs = require("fs");
    
    // This text file is used to store user account.
    var userAccountFile = "user_account.txt";
    
    var userAccountArray = null;
    
    // Create the write stream.
    var writeStream = fs.createWriteStream(userAccountFile, {
            flags: "a"
    });
    
    /* Register a user account. */
    function register(userName, password)
    {
        var ret = "";
    
        console.log("Register with " + userName + " , " + password);
    
        if(getUserAccount(userName).length > 0)
        {
    
            ret = "User name exist. Please use another one. ";
    
        }else {
    
            writeStream.write(userName);
            writeStream.write(" = ");
            writeStream.write(password);
            writeStream.write('\n');
    
            ret = "User account register success. "
        }
    
        console.log(ret);
    
        return ret;
    }
    
    
    /* Login with the user name and password. */
    function login(userName, password)
    {
        var ret = "";
    
        console.log("Login with " + userName + " , " + password);
    
        userName = trim(userName);
    
        if(userName.length > 0)
        {
            var userAccount = getUserAccount(userName);
    
            if(userAccount.length == 0)
            {
                ret = "User name do not exist.";
            }else
            {
                var userNamePasswordArray = userAccount.split("=");
    
                var passwordTmp = trim(userNamePasswordArray[1]);
    
                password = trim(password);
    
                if(passwordTmp == password)
                {
                    ret = "User name and password is correct. ";
                }else
                {
                    ret = "Password is not correct. "
                }
            }
        }
    
    
        console.log(ret);
    
        return ret;
    }
    
    /* Get and return user account text line by user name. */
    function getUserAccount(userName)
    {
        var ret = "";
    
        if(userAccountArray == null) {
    
            // Get all account data in the text file.
            var userAccountData = fs.readFileSync(userAccountFile);
    
            // Split each user account into an array.
            userAccountArray = userAccountData.toString().split("\n");
        }
    
        var size = userAccountArray.length;
    
        for(var i=0;i<size;i++)
        {
            var userAccount = userAccountArray[i];
    
            if(userAccount != '')
            {
                var userNamePasswordArray = userAccount.split("=");
    
                var userNameTmp = trim(userNamePasswordArray[0]);
    
                var passwordTmp = trim(userNamePasswordArray[1]);
    
                if(userName == userNameTmp)
                {
                    ret = userAccount;
                    break;
                }
            }
        }
    
        return trim(ret);
    }
    
    
    /* Remove the white space at the beginning and ending of the string. */
    function trim(str)
    {
        str = str.replace(/(^\s*)|(\s*$)/g, '');
        return str;
    }
    
    // Export login and register function for other Node js app to use.
    exports.login = login;
    
    exports.register = register;
  7. Now open a terminal and go to the CreatePublishUseCustomModule/node_modules/user_account directory, and execute the command npm pack to package the module.
    $ npm pack
    
    npm notice
    
    npm notice ?  @jerry-zhao/[email protected]
    
    npm notice === Tarball Contents ===
    
    npm notice 461B  package.json          
    
    npm notice 266B  README.md             
    
    npm notice 1.2kB user_account-1.0.0.tgz
    
    npm notice 2.6kB user_account.js       
    
    npm notice 15B   user_account.txt      
    
    npm notice === Tarball Details ===
    
    npm notice name:          @jerry-zhao/user_account                
    
    npm notice version:       1.0.0                                   
    
    npm notice filename:      jerry-zhao-user_account-1.0.0.tgz       
    
    npm notice package size:  2.8 kB                                  
    
    npm notice unpacked size: 4.5 kB                                  
    
    npm notice shasum:        325a5316679c23bd8f1edc261a33a1bf125357bf
    
    npm notice integrity:     sha512-kWW3d+F48f+B9[...]O8CEhNsgkgPPA==
    
    npm notice total files:   5                                       
    
    npm notice
    
    jerry-zhao-user_account-1.0.0.tg
    

2. How To Publish The Custom Node JS Module.

  1. Now the custom node js module package has been created, if you want to share it with others to use, you can publish the module in https://www.npmjs.com/ as public, then other node js developers can use it in their node app.
  2. Open a terminal and if you have not registered an account in https://www.npmjs.com/ then you should run the below command to register one.
    $ npm adduser
  3. After that go to the custom module directory in the terminal and execute the $ npm publish command. But you may encounter below npm publish error.
    publish Failed PUT 402
    
    npm ERR! code E402
    
    npm ERR! You must sign up for private packages : @jerry-zhao/user_account
  4. To resolve this error you need to add –access=public at the end of the command. This makes your node js module totally public.
    $ npm publish --access=public
    
    npm notice
    
    npm notice ?  @jerry-zhao/[email protected]
    
    npm notice === Tarball Contents ===
    
    npm notice 461B  package.json                     
    
    npm notice 2.8kB jerry-zhao-user_account-1.0.0.tgz
    
    npm notice 266B  README.md                        
    
    npm notice 1.2kB user_account-1.0.0.tgz           
    
    npm notice 2.6kB user_account.js                  
    
    npm notice 15B   user_account.txt                 
    
    npm notice === Tarball Details ===
    
    npm notice name:          @jerry-zhao/user_account                
    
    npm notice version:       1.0.0                                   
    
    npm notice package size:  5.8 kB                                  
    
    npm notice unpacked size: 7.4 kB                                  
    
    npm notice shasum:        f17ca8fea580b72a0984bf582407621778f3e278
    
    npm notice integrity:     sha512-XMTOIvV/Z5Idh[...]I8YXoY9i62N3g==
    
    npm notice total files:   6                                       
    
    npm notice
    
    + @jerry-zhao/[email protected]
  5. After the node js module publishing process is complete, you can find the module on your npmjs.com account packages list page.

3. How To Includes And Use The Node JS Custom Module.

  1. Now you can require the above module in your node js app source code and use it following the below steps.
  2. Install the custom node js module with root privilege.
    $ su
    
    Password:
    
    sh-3.2# npm install @jerry-zhao/user_account -g
    
    + @jerry-zhao/[email protected]
    
    added 1 package from 1 contributor in 2.884s
  3. Now you can find the module has been added in the node global library folder /usr/local/lib/node_modules/@jerry-zhao/user_account.
  4. To use the custom node js module, create a js file ( the test_user_account_module.js file in this example ) in the project folder.
  5. test_user_account_module.js
    // Import custom user account module.
    var userAccount = require("@jerry-zhao/user_account");
    
    userAccount.register('tom', '8888888');
    
    userAccount.login('tom', '11111111');
    
    userAccount.login('jerry', '11111111');
    
    userAccount.login('tom', '8888888');
  6. Run above node js code, and you can get the below output int your console.
    /usr/local/bin/node /Users/zhaosong/Documents/WorkSpace/dev2qa.com-example-code/JavaScriptExampleWorkspace/NodeJSWorkspace/CreatePublishUseCustomModule/test_user_account_module.js
    Register with tom , 8888888
    User name exist. Please use another one. 
    Login with tom , 11111111
    Password is not correct. 
    Login with jerry , 11111111
    User name do not exist.
    Login with tom , 8888888
    User name and password is correct.
    
    Process finished with exit code 0
  7. If the node js show below error messages which said can not find the module. Then you should add the node_modules global folder in the system NODE_PATH system variable value.
    Error: Cannot find module 'user_account_demo'
    
    at Function.Module._resolveFilename (module.js:547:15)
    
    at Function.Module._load (module.js:474:25)
    
    at Module.require (module.js:596:17)
    
    at require (internal/module.js:11:18)
    
    at Object.<anonymous> (/Users/zhaosong/Documents/WorkSpace/dev2qa.com-example-code/JavaScriptExampleWorkspace/NodeJSWorkspace/CreatePublishUseCustomModule/test_user_account_module.js:2:19)
    
    at Module._compile (module.js:652:30)
    
    at Object.Module._extensions..js (module.js:663:10)
    
    at Module.load (module.js:565:32)
    
    at tryModuleLoad (module.js:505:12)
    
    at Function.Module._load (module.js:497:3)
  8. In macOS, you need to edit the user /Users/<user name>/.bash_profile file like below.
    $open -e .bash_profile
    Add
    export NODE_PATH="/usr/local/lib/node_modules" in it and close the popup window to save the changes.
    Execute

    source .bash_profile

     command in terminal window again to make it take effect.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.