Click here to Skip to main content
15,867,756 members
Articles / Web Development / Node.js

Learn Step-by-Step How to Create nodejs Module and Publish Over to NPM

,
Rate me:
Please Sign up or sign in to vote.
5.00/5 (6 votes)
10 Apr 2015MIT7 min read 31K   226   12   11
In this article, we will discuss how to create npm packages/modules

Contents

Introduction

In this article, we will create a small package/module to use with nodejs or as a JavaScript standalone library.

Purpose

Here, our purpose is to get started with creation of npm packages. We will start with a simple npm package and explain the same. In coming articles, we will discuss more in detail.

Pre-requisite

To get started with this series, you should be aware of:

  • NodeJs
  • npm
  • Bower
  • Basic knowledge of JavaScript

You should:

  • have a valid user account with npm
  • have installed nodejs on your machine

Need of npm Package

While I was working on a real time nodejs application, I came to many instances where I have to write few libraries. Lately, I thought these libraries can be useful for others. Afterwards, I reached npm package.

What is npm?

So, the first question that would be in our mind is about npm, what is it actually?

In my view, npm is a package repository, where we can deploy/store our libraries as a packages. Library can be anything in JavaScript. Here, we can update/upgrade and version our repositories. For more details, refer to What is npm?

Get Started with Creation of npm Package

Creation of npm package is fairly simple. Before that first, install nodejs, we are not going to discuss the process of installation of nodejs here, which is beyond our scope. For more information, refer to Install nodejs.

After installation, make sure to check the versions, type the following on command line from your terminal, you can also use Powershell for Windows:

node -v
npm -v

Now, we are ready to start building our first npm/nodejs package. I suggest you go to http://npm.com and register yourself, we will use this account later in this article.

Start Writing the Actual Code

Following steps describe how to go about with the creation of our example package:

Describing Our Demo App

In our demo app, we will build a package, which converts a number to text/words. To make it simple, initially we are accepting only integers no decimals allowed. Also, I am making it strict to 'Indian system to read numbers' viz. Thousand, Ten Thousand, Lakh, Ten Lakh, etc.

After completion of this package, we can get the following output for a specific number:

//1000 will be read as One Thousand

1000 = One Thousand

Get It Started

To start our actual coding stuff, let's clone your GIT repository (we have already created our GIT repo) on your local system. Pass the following command from your GIT Bash or any other GIT tool (whatever you like). I am going to use GIT Bash.

MC++
git clone https://github.com/garora/number2text.git
cd number2text

Refer to the following image for more description:

Image 1

Now, we are ready to start creating our package information, pass the following command in GIT Bash...

MC++
npm init

...and it will create package.json file, which is nothing but just creating a data in the form of json of your package. Refer to https://docs.npmjs.com/json.

Complete the information, see the snapshot for more description:

Image 2

After hitting enter as ok, our package.json would look like:

{
  "name": "number2text",
  "version": "0.1.0",
  "description": "A small utility converts Number to Text
  (supports to Indian numbers only with initial release).",
  "main": "index.js",
  "scripts": {
    "test": "make test"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/garora/number2text.git"
  },
  "keywords": [
    "number",
    "text"
  ],
  "author": "Gaurav Kumar Arora <g_arora@hotmail.com> (http://gaurav-arora.com/)",
  "license": "MIT",
  "url": "https://github.com/garora/number2text/blob/master/LICENSE",
  "bugs": {
    "url": "https://github.com/garora/number2text/issues"
  },
  "homepage": "https://github.com/garora/number2text",
  "devDependencies": {
    "mocha": "^2.2.1",
    "chai": "^2.2.0"
  }
}</g_arora@hotmail.com>

As we will grow with the code, we will change package.json file contents.

You can see, in package.json, we have index.js as our main. Before we start creation of our main file, let's create a library that we will be using for our package.

Go to GIT Bash and add a new folder called lib, by passing the following command:

mkdir lib

and after that, get into lib folder/directory:

cd lib

Now, choose your favourite editor to write JavaScript code. I am going to chose Sublime Text. Now, create a new js file and named it numberToText.js under lib folder.

Add the following code in the file:

function numberToText(num)
{
  if(isNaN(num))
     return "Invalid number.";

  if(!isInt(num))
    return "Currently support for decimal is unavailable.";

  if(!isInRange(num))
    return "Please enter number between 0 - 999999999.";

  return toText(num,'Indian'); //currently supports for Indian number conversions
}

...
//Rest part of code has been removed
...
  • Code Explanation

    In the above, we are writing a code to accept only number, integers within a range <var>0 - 999999999</var>.

    Add exports so that we can use this library in our main js file.

    //export
      module.exports = numberToText;

    Please refer to the attached demo source code for full contents of the above code-snippet.

Now, in our main folder, create a new file and name it index.js. Now, add the following code-snippet so that we can get the functions of our library.

var numberToText = require('./lib/numberToText');

Here, we are getting object of our library and then here is our main module:

module.exports = function (num) {
    return numberToText(num);
  };

Finally, we are done with all our things that we wanted to add in our package.

Execute Tests

Let's run our tests now, go to package.json file and update the test node with the following:

"test": "./node_modules/.bin/mocha"

Publish to npm

Finally, we are going to publish our package. I always prefer to test our package before publishing, here test does not mean to write test, but it does mean to verify that package should install successfully. To do so, pass the following command (make sure you're on the root directory of package):

npm install . -g

Verify install:

npm ls -g
  • Test npm Package/Node Module

    After completion of all our things with the code, we need to make sure that all is working fine. The very first approach is to write tests. So, let's start and write some tests.

    Before we start writing test cases, we should need to choose test framework, I choose Mocha and Chai. You can choose whatever you prefer.

    Now, install these frameworks so that we can start writing tests:

    npm install mocha --save-dev
    npm install chai --save-dev
    

    Did you notice? We are installing these two as dev dependencies, why? Just because we need these two during our development and these are not required while someone is actually going to use our module/package. These will be installed in new folder called node_modules. We do not require this folder for our users, then why should we check-in this folder. To ignore this folder, there is a .gitignore file. Just go and add this file at root level and add the following:

    node_modules

    It will tell GIT that we should ignore this folder while making check-ins.

    Go and create a new folder named test and create file named index.js under this folder. and write our first test:

    Declare test framework:

    var should = require('chai').should(),
          number2text = require('../index');

    Our test:

    describe('Negative Tests', function() {
        
        it('Test for invalid number', function() {
          number2text('N').should.equal('Invalid number.');
        });
    
       it('Test for decimal', function() {
          number2text('10.10').should.equal('Currently support for decimal is unavailable.');
        });
    
      it('Out of range - Lower', function() {
          number2text(-1).should.equal('Please enter number between 0 - 999999999.');
        });
    
      it('Out of range - Higher', function() {
          number2text(1000000000).should.equal('Please enter number between 0 - 999999999.');
        });
      });
  • Now, we are ready to run tests. Pass the following command from your GIT Bash:
    npm test

    You would see the following screen:

    Image 3

    Make sure that all tests should pass.

    Add README.md File

    We are all done with the package creation. Now, it's time to describe our package, here under we are going to add a typicalReadMe file, with markdown notations.

    I grouped a typical readme file as:

    Title and description

    This is self-explanatory. It tells about the module/package name with a short description.

    ## number2text
      A small utility converts Number to Text (supports to Indian numbers only with initial release).

    Installation instruction

    In this section, let's tell the user how they can install the package:

    npm install number2text --save

    Instruction to use the package/module

    Here, you should provide few examples of usage:

    # How to use?
    
        var numberToText = require('number2text');
        var textDefault = numberToText(100); //it converts to default type i.e. Indian
    
        console.log('Converts 1000000 to ', textDefault); //Converts 1000000 to Ten Lakh    

    Release History

    A typical release history numbers in the form of major.minor.patch. For more information, refer to http://semver.org/.

    Open package.json file and update your version as:

    "version": "0.0.1"

    License

    This is a very important section of Readme, here you are letting people know how you want to offer your package. I am using MIT License as:

    The MIT License (MIT)
    
      Copyright (c) 2015 Gaurav Kumar Arora

    Go to package.json file and update License information as:

    "licenses": [
         {
           "type": "MIT",
           "url": "http://www.opensource.org/licenses/MIT"
         }
     ]
    
    • Here, we are defining our license type and a referred URL, which tells us the details of the license.

      Go to http://opensource.org/licenses/alphabetical and get contents of MIT license. Then add these contents to your new file named License.

    Hurrah! We are done with this. Now, pass the following commands from GIT Bash to make sure that we pushed all things to our GIT repo:

    git tag 0.0.1
      git push origin master --tags
    In GIT tag is a release number.
  • It lists all installed packages. If your package is listed, then you have successfully installed it.

    To get a hit, switch to another directory and pass the following commands:

    node
    var numberToText = require('number2text');
    var textDefault = numberToText(100);
    console.log('Converts 1000000 to ', textDefault);
    

    You would get the following screen:

    Image 4

    Now, finally publish your package over npm by passing the following command:

    npm publish

    Go to http://npmjs.com login and check your published package. We have published here: number2text.

Conclusion

In this article, we have discussed how to create, publish npm package in simple step(s).

Points of Interest

We should remember these bulleted points while working with creation of npm packages:

  • require - we would require other modules for our modules, we also called module dependencies, etc.
  • exports - we should want that others can use our modules, so, we have to export the module publicly.

Further Reading

Hope, you enjoyed reading this article. I suggest reading the following articles to play with the demo application and enjoy the taste of npm (make a pull request, if you want any modifications:

License

This article, along with any associated source code and files, is licensed under The MIT License


Written By
Doctorandin Technische Universität Berlin
Iran (Islamic Republic of) Iran (Islamic Republic of)
I have been working with different technologies and data more than 10 years.
I`d like to challenge with complex problem, then make it easy for using everyone. This is the best joy.

ICT Master in Norway 2013
Doctorandin at Technische Universität Berlin in Data Scientist ( currently )
-------------------------------------------------------------
Diamond is nothing except the pieces of the coal which have continued their activities finally they have become Diamond.

http://www.repocomp.com/

Written By
Chief Technology Officer
India India
Learning never ends.

Comments and Discussions

 
QuestionFunction name and Page name are the same... Pin
Member 1341644118-Sep-17 13:46
Member 1341644118-Sep-17 13:46 
First off thank you for taking the time to put together this step by step tutorial it has been very helpful.  The only part that I found confusing is that you used the same name for the page, the "var" in index.js and the function itself, "numberToText".  My question is, if you were to give the function a different name which part of the script in index.js would change? Does the "export" at the bottom of "numberToText.js" refer to the page name or the name of the function? Thank you for clarifying.

A Nube

AnswerRe: Function name and Page name are the same... Pin
Gaurav Aroraa25-Sep-17 1:23
professionalGaurav Aroraa25-Sep-17 1:23 
PraiseGreat article Pin
Michael Haephrati12-Sep-17 2:45
professionalMichael Haephrati12-Sep-17 2:45 
GeneralNice to see two good authors together Pin
Shuby Arora13-Apr-15 4:44
Shuby Arora13-Apr-15 4:44 
GeneralRe: Nice to see two good authors together Pin
Gaurav Aroraa13-Apr-15 20:23
professionalGaurav Aroraa13-Apr-15 20:23 
GeneralRe: Nice to see two good authors together Pin
Mahsa Hassankashi16-Apr-15 0:45
Mahsa Hassankashi16-Apr-15 0:45 
GeneralRe: Nice to see two good authors together Pin
Gaurav Aroraa16-Apr-15 7:07
professionalGaurav Aroraa16-Apr-15 7:07 
GeneralRe: Nice to see two good authors together Pin
Gaurav Aroraa16-Apr-15 7:08
professionalGaurav Aroraa16-Apr-15 7:08 
GeneralRe: Nice to see two good authors together Pin
Mahsa Hassankashi16-Apr-15 0:43
Mahsa Hassankashi16-Apr-15 0:43 
Generalmy vote for 5 Pin
Shuby Arora13-Apr-15 4:42
Shuby Arora13-Apr-15 4:42 
GeneralRe: my vote for 5 Pin
Gaurav Aroraa13-Apr-15 20:24
professionalGaurav Aroraa13-Apr-15 20:24 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.