Contents
In this article, we will create a small package/module to use with nodejs or as a JavaScript standalone library.
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.
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
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.
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?
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.
Following steps describe how to go about with the creation of our example package:
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
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.
git clone https:cd number2text
Refer to the following image for more description:
Now, we are ready to start creating our package information, pass the following command in GIT Bash...
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:
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.
Let's run our tests now, go to package.json file and update the test node with the following:
"test": "./node_modules/.bin/mocha"
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:
Make sure that all tests should pass.
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:
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).
In this section, let's tell the user how they can install the package:
npm install number2text --save
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
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"
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"
}
]
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:
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.
In this article, we have discussed how to create, publish npm package in simple step(s).
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.
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: