How to Create Nodejs Module and Publish Over to Npm

Contents

• History
• Introduction
• Purpose
• Prerequisites
• Need of npm package
• What npm is
• Get started with creation of npm package
• Start writing actual code 
      o Get ready with npm
      o Create GIT repository
      o Start writting node module/npm package 
         o Two thumbs for node modules
         o Describing our demo app
         o Get it started
• Test npm package/node module
• Execute tests
• Add README.md file 
     o Title and description
     o Installation instruction
     o Instruction to use the package/module
     o Release History
     o License
• Publish to npm
• Conclusion
• Points of interest
• Link to official npm site


History

In the previous article of this series, we saw the release of NodeJS tools for Visual Studio. In this article, we will procede a step ahead and learn how to create and publish a nodejs module or npm package.

I suggest the following reading(s) before starting with this article:

Getting Start With Node.JS Tools For Visual Studio

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 the creation of npm packages. We will start with a simple npm package and explain that. In future articles, we will discuss more in details.

Prerequisites

To get started with this series you should be aware of:
  • NodeJs
  • npm
  • Bower
  • Basic knowledge of JavaScript

You should also:

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

Need of npm package

While I was working on a real nodejs application I encountered many instances where I needed to write a few libraries. Lately, I thought these libraries can be useful for others. Afterward, I discovered the npm package.

What npm is

So First question that would be in our mind about npm is, what is it actually? In my view, npm is a package repository, where we can deploy/store our libraryies as packages. A 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 a npm package is farely simple. Before that, first install nodejs. We wiil not discuss the process of the installation of nodejs here, that is beyond the scope of this article. For more info, refer to: Install nodejs.

After installation be sure to check the versions, enter the following on the command line from your terminal, you can also use PowerShell for Windows:

  1. node –v  
  2. npm -v  
We are now ready to start building our first npm/nodejs package. I suggest going to http://npm.com and register yourself, we will use this account later in this article.

Start writing actual code

The following procedure describes how to create our example package.

Get ready with npm

The very first step is to configure, or get ready with, our npm. We have already registered with npm, now it's time to setup our npm locally so, when we'll start to enter the actuall information, all will be available.

An an example, here I am providing my information, you need to provide your own.

Set Author Name
  1. npm set init.author.name "Gaurav Kumar Arora"  
Set Author Email
  1. npm set init.author.email "[email protected]"  
Set Author Website
  1. npm set init.author.url "http://gaurav-arora.com"  
Add user in npm registry
  1. npm adduser  
With the preceding command, you will be adding a verified user via username and password to the npm registry, please use the following instructions and provide the relevant information.

Create GIT repository

Although this is not necessary, you should have a GIT repository to create the node module/npm package. For the developer's convenience, I created a Git repository at: number2text.

In this article, we will use this GIT repository for our demo application.

Start writting node module/npm package

Before beginning anything, I suggest first readinig the Commonjs specs. These are the standards, we will be using it in our demo and it is usually followed by node module/npm package developers.

Now, a question that should be in our mind, what is a node module/npm package all about? The answer is very simple, it's nothing but a common JavaScript file that must follow the CommonJS module spec.

The interesting thing about node modules is that they run under their own scope, in this way modules don't clash with each other.

Two thumbs for node modules

I called it as thumbs since they are very important in the life of node modules, we should keep the following two in our mind.

require

We should require other modules for our modules, we also call module dependencies and so on.

 

  1. var numberToText = require('other_numberToText');  
exports

We should want that others can use our modules, so we need to export the module for publicly.
  1. module.exports = function ()  
  2.  {  
  3. return numberToText(); //this is an internal function which changes number to words/text  
  4. };  
Combining these two, our module looks as in:
  1. var numberToText = require('other_numberToText');  
  2.   
  3. module.exports = function (num,type)  
  4.  {  
  5. return numberToText(num,type);  
  6. };  
Describing our demo app

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

After the completion of this package we can get the following output for a specific number:
  1. //1000 will be read as One Thousand  
  2. 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 will use GIT Bash.
  1. git clone https://github.com/garora/number2text.git  
  2.   
  3. cd number2text  
 Refer to the following image for further description.



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

npm init

And it will create a package.json file that does nothing but create data in JSON format of your package. Refer:https://docs.npmjs.com/json

Complete the info, see the following snapshot for further description.



After hitting Enter as OK, our package.json would look like:
  1. {  
  2. "name""number2text",  
  3. "version""0.1.0",  
  4. "description""A small utility converts Number to Text (supports to Indian numbers only with initial release).",  
  5. "main""index.js",  
  6. "scripts": {  
  7. "test""make test"  
  8. },  
  9. "repository": {  
  10. "type""git",  
  11. "url""https://github.com/garora/number2text.git"  
  12. },  
  13. "keywords": [  
  14. "number",  
  15. "text"  
  16. ],  
  17. "author""Gaurav Kumar Arora (http://gaurav-arora.com/)",  
  18. "license""MIT",  
  19. "url""https://github.com/garora/number2text/blob/master/LICENSE",  
  20. "bugs": {  
  21. "url""https://github.com/garora/number2text/issues"  
  22. },  
  23. "homepage""https://github.com/garora/number2text",  
  24. "devDependencies": {  
  25. "mocha""^2.2.1",  
  26. "chai""^2.2.0"  
  27. }  
  28. }  
As we will grow with the code, we will change the package.json file contents.

You can see, in package.json, we have index.js as our main. Before beginning to create our main file, let's create the library we will be using for our package.

Go to GIT Bash and add a new folder called lib, by passing the following command:
  1. mkdir lib  
And then go to the lib folder/directory:
  1. cd lib  
Now, choose your favourite editor to write JavaScript code. I will chose Sublime Text. Now, create a new JavaScript file and name it numberToText.js under the lib folder.

Add the following code in the file:
  1. function numberToText(num)  
  2. {  
  3.   
  4. if(isNaN(num))  
  5. return "Invalid number.";  
  6.   
  7. if(!isInt(num))  
  8. return "Currently support for decimal is unavailable.";  
  9.   
  10. if(!isInRange(num))  
  11. return "Please enter number between 0 - 999999999.";  
  12.   
  13. return toText(num,'Indian'); //currently supports for Indian number conversions   
  14. }   
  15.   
  16. ...  
  17. //Rest part of code has been removed  
  18. ...  
Code explanation

In the preceding, we are writting code to accept only a number, integers within the range 0 - 999999999.

Add exports. So that we can use this library in our main JavaScript file.
//export
  1. module.exports = numberToText;  
Please refer to attached demo source code for full contents of the preceding 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.
  1. var numberToText = require('./lib/numberToText');  
Here, we are getting an object of our library and then here is our main module:
  1. module.exports = function (num)  
  2.  {  
  3.     return numberToText(num);  
  4. };  
Finally, we are done with everything to be added to our package.

Test npm package/node module

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

Before beginning to write test cases, we should choose a test framework, I chose Mocha adn Chai. You can choose whatever you prefer.

Now, install these frameworks, so we can stat writting tests:
npm install mocha --save-dev  

  1.   
  2. npm install chai --save-dev  
Did you notice? We are installing these two as a dev dependencies, why? Just because we need these two during our development and these are not required when someone will actually use our module/package. These will be installed in a new folder called node_modules. We do not require this folder for our users, so why should be check-in this folder? To ignore this folder there is a .gitignore file. Just go and add this file at the root level and add the following:
  1. node_modules  
It will tell GIT that we should ignore this folder when making check-ins.

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

declare test framework:

 

  1. var should = require('chai').should(),  
  2. number2text = require('../index');  
  3. our test:   
  4. describe('Negative Tests'function() {  
  5.   
  6. it('Test for invalid number'function() {  
  7. number2text('N').should.equal('Invalid number.');  
  8. });  
  9.   
  10. it('Test for decimal'function() {  
  11. number2text('10.10').should.equal('Currently support for decimal is unavailable.');  
  12. });  
  13.   
  14. it('Out of range - Lower'function() {  
  15. number2text(-1).should.equal('Please enter number between 0 - 999999999.');  
  16. });  
  17.   
  18. it('Out of range - Higher'function() {  
  19. number2text(1000000000).should.equal('Please enter number between 0 - 999999999.');  
  20. });  
  21.   
  22. });  
Execute tests

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

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

We are now ready to run the tests. Pass the following command from your GIT Bash:

npm test

You would see the following screen.



Be sure that all the tests pass.

Add README.md file

We are all done with package creation. It's now time to describe your package, here we will add a typicalReadMe file, with markdown notations.

I grouped a typical readme file as in the following.

Title and description

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

## number2text

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

Installation instruction

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

  1. npm install number2text --save  
Instruction to use the package/module

Here are a few examples of the use. 

 

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

A typical release history numbes in the form of major.minor.patch. For more info refer:http://semver.org/

Open the package.json file and update your version as:
  1. "version""0.0.1"  
License

This is a very important section of the Readme, here you are letting people know how you want to offer your package. I am using the MIT License as in the following:
  1. The MIT License (MIT)  
  2.   
  3. Copyright (c) 2015 Gaurav Kumar Arora  
  4.   
  5. Go to package.json file and update License info as:  
  6.   
  7. "licenses": [  
  8. {  
  9. "type""MIT",  
  10. "url""http://www.opensource.org/licenses/MIT"  
  11. }  
  12. ]  
Here, we are defining our license type and a referred URL that tells us the details of the license. 

Go here: http://opensource.org/licenses/alphabetical and get the contents of the 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 be sure we pushed everything to our GIT repo:
  1. git tag 0.0.1  
  2.   
  3. git push origin master --tags  
In GIT tag is a release number.

Publish to npm

Finally, we will publish our package. I always prefer to test the package before publishing, here test does not mean to write a test, it does mean to verify that the package installs successfully. To do so, pass the following command (be sure you're on the root directory of the package):
  1. npm install . -g  
Verify install:
  1. npm ls -g  
It lists all the 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:
  1. node  
  2. var numberToText = require('number2text');  
  3. var textDefault = numberToText(100);  
  4. console.log('Converts 1000000 to ', textDefault);  
You would get the following screen:



Now, finally publish your package over npm by passing the following command:
  1. npm publish  
Go to http://npmjs.com then login and check your published package. We have published here: number2text.

Conclusion

This article has explained how to create and publish the npm package in simple step(s).

Further reading

I hope you enjoyed reading this. I suggest reading the following to play with the demo application and enjoy the taste of npm (make a pull request, if you want any modifications).
Link to official site

You can also visit npm official website and search for this node module. If you would like to add new feature please feel free to fork the repository and pull your changes.


Similar Articles