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 StudioIntroduction
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:
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
- npm set init.author.name "Gaurav Kumar Arora"
Set Author Email Set Author Website - npm set init.author.url "http://gaurav-arora.com"
Add user in npm registry 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.
- var numberToText = require('other_numberToText');
exports
We should want that others can use our modules, so we need to export the module for publicly.
- module.exports = function ()
- {
- return numberToText();
- };
Combining these two, our module looks as in:
- var numberToText = require('other_numberToText');
-
- module.exports = function (num,type)
- {
- return numberToText(num,type);
- };
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:
- //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 will use GIT Bash.
- git clone https://github.com/garora/number2text.git
-
- 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/jsonComplete the info, see the following snapshot for further description.
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 (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"
- }
- }
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:
And then go to the lib folder/directory:
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:
- 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');
- }
-
- ...
-
- ...
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
- 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.
- var numberToText = require('./lib/numberToText');
Here, we are getting an object of our library and then here is our main module:
- module.exports = function (num)
- {
- return numberToText(num);
- };
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
-
- 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:
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:
- 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.');
- });
-
- });
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:
- npm install number2text --save
Instruction to use the package/module
Here are a few examples of the 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 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:
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:
- The MIT License (MIT)
-
- Copyright (c) 2015 Gaurav Kumar Arora
-
- Go to package.json file and update License info as:
-
- "licenses": [
- {
- "type": "MIT",
- "url": "http://www.opensource.org/licenses/MIT"
- }
- ]
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:
- git tag 0.0.1
-
- 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):
Verify install:
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:
- node
- var numberToText = require('number2text');
- var textDefault = numberToText(100);
- console.log('Converts 1000000 to ', textDefault);
You would get the following screen:
Now, finally publish your package over npm by passing the following command:
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 readingI 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.