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.

This custom node js module contains five files. package.json, README.md, user_account.js, user_account.txt and jerry-zhao-user_account-1.0.0.tgz.

node js custom package module source files

  1. 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 provide user account register and login function.
  2. Then open a terminal and go to above folder and execute command npm init in command line. This command will guide you to create the module. You can refer How To Create Custom NPM Modules to learn more.
  3. After above process, 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 user 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"
    }
  4. 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.
  5. Now create the js file user_account.js and input 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;
  6. Now open a terminal and goto CreatePublishUseCustomModule/node_modules/user_account directory, and execute npm pack command 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.

Now the custom node js module package has been created, if you want to share it to others to use, you can publish the module in https://www.npmjs.com/ as public, then other node js developer can use it in their node app.

  1. Open a terminal and if you have not register an account in https://www.npmjs.com/ then you should run below command to register one.
    $ npm adduser
  2. After that go to the custom module directory in terminal and execute $ 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
  3. To resolve this error you need to add –access=public at the end of the command. This make 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]
  4. After the node js module publish process, you can find the module in your npmjs.com account packages list page.
    npmjs.com user custom node js module package list page
READ :   Node JS EventEmitter Example

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

Now you can require above module in your node js app source code and use it follow below steps.

  1. 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
  2. Now you can find the module has been added in the node global library folder /usr/local/lib/node_modules/@jerry-zhao/user_account.
  3. To use the custom node js module, create a js file in the project folder.
    node js custom module test file
    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');
  4. Run above node js code, and you can get below output int you 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
  5. 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)
  6. 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.
(Visited 113 times, 2 visits today)

Leave a Reply

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.