Building your first Node.js module

by Jonathan Fielding on December 8, 2014

The modern web is always changing, and this article is more than two years old.

One of things that makes Node.js so popular is the way in which code can be structured into modules that can be reused from project to project. Not only are you able to reuse your own modules, there is a vibrant community of developers who are developing and releasing their own modules as open source for anyone to use in their own projects. It’s these modules that you will find packaged on the Node Package Manager (NPM).

Whether you want to write code in a way that you can reuse time and time again in your own projects or to build something you can release to the public, writing it as a Node.js module can be really valuable. In this tutorial we will explore how we can write our own Node.js module that will take an array of integers and add them together, returning the final value.

What is a Node.js Module?

Before we get started with building our Node.js module, it is important that we understand what a Node.js module is. In its simplest form, a Node.js module is a JavaScript file which is built to follow the CommonJS module specification. It encapsulates related functionality into a reusable file that can be used across multiple projects.

Modules are loaded by using “require” with which they can be loaded directly using a file path, or in the case where the module is located in the “node_modules” folder of your project, they can simply be loaded using the module name.

Building your first Node.js Module

In this example our node module will take an array of numbers as an argument and then return the result of adding them together. We will start by ensuring we have Node.js set up, set up version control and then write the functionality. After writing our module we will use Jasmine to test it, then publish it to NPM.

Setting up your project

Before we get started we need first need to set up the dependencies. For this project we will need to set up the following:

  • Node.js
  • Git repository

Installing Node.JS

There are several ways in which you can install Node.js on your system

  • Using Homebrew (Mac only) – brew install node
  • Downloading the installer from http://nodejs.org

Having installed Node.js we will now configure NPM with our details so that it knows who we are when we later create our module. To configure our details we use the “npm set” command which allows us set default values. In this instance we will set up the values for our name, email and our website URL. The full commands are:

npm set init.author.name "Jonathan Fielding"
npm set init.author.email "[email protected]"
npm set init.author.url “http://modernweb.com"

Creating your Git repository

To allow us to manage the source code of our module we will want to use a version control system (VCS). For this tutorial we will be using Git and as the module we are writing will be open source and published on NPM, we will be create our repository on GitHub (http://www.github.com).

To create a repository on GitHub you will first need an account, so if you currently don’t have a GitHub account I advise you create one. Outside of this tutorial having a GitHub account can be very valuable as it will allow you to contribute to open source projects alongside running your own.

Once you are in your account you need to visit https://github.com/new to create your repository. For this tutorial I recommended you check the “Initialize this repository with a README” box so that you can simply clone the repository locally.

To clone the repository we use the git clone command in our terminal, passing it the URL to your GitHub repository as a parameter (this URL is found at the bottom of the right hand column. You might need to toggle the URL that is shown to be the HTTPS URL, as we will be using that in this tutorial). We can then simply run the command as follows (replacing the URL with your own GitHub repo URL):

git clone https://github.com/jonathan-fielding/AddAll.git

If you are using a public repository, the repository will simply clone. For a private repository you will now be asked for your username and password for your GitHub account, once these are entered your computer will clone the repository to your hard disk.

See Also:  How Cars.com Developer Mac Heller-Ogden Convinced His Bosses to Adopt Node.js

Once cloned we can then move on to initializing our module.

Initializing the Node.js Module

Having set up our dependencies for this project we can now initialize our module, to do this we can use the “npm init” command line tool.

To start with you will need to ensure you are in the directory where we checked out the Git repository we created on GitHub. We then run the command:

npm init

This will start the process of initializing your Node.js Module which you will be ask you a series of questions:

name: (AddAll)
version: (1.0.0)
description: A node module that will add all the numbers in an array together
entry point: (index.js)
test command:
git repository: (https://github.com/jonathan-fielding/AddAll.git)
keywords: add numbers
license: (ISC) MIT

You will notice that next to some of the questions is some brackets containing some text, this is a suggested value and to accept this as the value you can simply hit the enter key. The values shown in bold are those which I had to specify myself.

After answering the questions, the npm init command will automatically generate you a package.json file, the contents for this project being:

{
"name": "AddAll",
"version": "1.0.0",
"description": "A node module that will add all the numbers in an array together",
"main": "index.js",
"scripts": {
"test": "echo "Error: no test specified" && exit 1"
},
"repository": {
"type": "git",
"url": "https://github.com/jonathan-fielding/AddAll.git"
},
"keywords": [
"add",
"numbers"
],
"author": "Jonathan Fielding <[email protected]> (http://modernweb.com/)",
"license": "MIT",
"bugs": {
"url": "https://github.com/jonathan-fielding/AddAll/issues"
},
"homepage": "https://github.com/jonathan-fielding/AddAll"
}

Having initialized our module we can now make a start on putting the code together.

Building the Node.js Module

Node.js modules expose their functionality through assigning a value to module.exports, this allows us to select what we want accessible to the code that is requiring our module. The most popular options of what to expose are anonymous functions or objects containing values, methods that can be called. In this example we only need a simple function that will add up our numbers, so we will expose an anonymous function.

As our function will take an array of numbers we will need to give a name to the argument, for simplicity we will just call it “numbers”. With this is mind, our code looks like this:

module.exports = function (numbers) {

};

The next step is for us to loop through the array and calculate a value. To do this we will have a variable called “value” which we will increment with the value of each item in the array of numbers.

module.exports = function (numbers) {
var value = 0;
for (var i = 0; i < numbers.length; i++) {
value = value + numbers[i];
}
return value;

};

Having written the module we now need to test that it works as we expect.

Testing our Node.js Module

To test our Node.js Module we will use the Node.js specific version of the Jasmine testing framework. To get started with Jasmine, we will first need to install it globally on your system using the following command:

npm install jasmine-node -g

Having installed Jasmine we now need to create a test specification which is used to test our module. These should be placed in a folder called “spec”. We will then create the specification that will describe the functionality of our module and test that we get back the expected results. To do this we will create a file called “addall.spec.js” inside our “spec” folder.

Inside addall.spec.js we first need to require the AddAll index.js file that we created, we do this as follows:

var AddAll = require('../index.js');

We can now describe our test suite as a series of tests, the first step in doing this is for us to run the “describe” method. The “describe” method takes two arguments; the first being the name of the test suite we are describing, and the second is a function which is used to define the tests that make up the test suite.

describe("AddAll Suite", function() {

});

The next step is for us to add tests to our test suite, for this example we will write three tests each passing a different array of values. For our first test we will use the numbers 1, 2 and 3 as the values in the array, and we will expect the answer to equal 6.

See Also:  Getting started with Redux using the Mullet Stack

To define a test we use the “it” method passing a name for our test and a method which will perform the actual test.

it("should respond with a value of 6", function(done) {

});

For the actual test we will set up a variable called “value” which we will store the value returned from our AddAll module after we pass it an array of numbers. We then use the “expect” method to pass the value returned by module, and then from this use “.toEqual” to tell the test the value we expect. To complete the test we then simply run the “done” method which was passed to the test as an argument.

it("should respond with a value of 6", function(done) {
var value = AddAll([1,2,3]);
expect(value).toEqual(6);
done();
});

Having written this first test we can simply duplicate the test passing different values to our AddAll module, testing for different values. Our final test suite looks like this:

describe("AddAll Suite", function() {
it("should respond with a value of 6", function(done) {
var value = AddAll([1,2,3]);
expect(value).toEqual(6);
done();
});
it("should respond with a value of 10", function(done) {
var value = AddAll([1,2,3,4]);
expect(value).toEqual(10);
done();
});
it("should respond with a value of -1", function(done) {
var value = AddAll([-10,2,3,4]);
expect(value).toEqual(-1);
done();
});
});

We can now test our module by running jasmine-node, telling it where our specifications are stored.

jasmine-node spec/

Screen Shot 2014-10-19 at 19.37.34

Our tests will then run and we should get information of how many pass and fail, in this example we had 3 tests and all passed.

Documenting our module

As we are intending to publish our module on NPM we need to ensure we provide some basic documentation on how we can use the module. Not only will this help others who use your module in the future but also will provide you with documentation on how to use it yourself when you return to use this module at a later date.

When working with an open source project, it is standard for the documentation to live in a “README.md” file. The “md” file extension is short for Markdown which is a document markup language that is not only simple to use but can be compiled to many different document formats, most commonly HTML.

The things you might want to include in your documentation:

  • License for use of the module
  • How to use the module (documenting the API it offers the developer using it)

Committing our module to Git

Having written our node module and tested that it works as intended we will now commit our work to the Git repository we created earlier. The first step is for us to navigate to the folder of our project in the terminal. Having followed this tutorial you should have the following files contained within it:

index.js

package.json

README.md

spec/

    addall.spec.js

As we want to add all these files to the Git repository, we can simply use the command:

git add .

this will add all untracked files to the repository.

Having added the files, we can now commit these files using the “git commit” command.

git commit -m "initial commit"

Publishing to a Node.js Module to NPM

Having completed the first version of our module we will want to publish it to NPM, the first step to do this is to create a user on NPM. To create your user use the command:

npm adduser

After running this you will be asked to provide a username, password and your email address. The credentials for which will be stored to the ~/.npmrc file.

The next step is to publish our module, to do this we use the command:

npm publish

Having published the module you should be able to create a new directory on your system, navigate to it in the Terminal and then install the module using NPM. In this case the command would be:

npm install AddAll

Your module will now be installed into the directory.

Summary

In this tutorial we looked at how we could create our own Node.js Module, write unit tests to ensure that it worked properly and then publish it to NPM.

Using Node.js Modules can be really beneficial to your project as their reusable nature means that you can write once, reuse anywhere. In addition, publishing your nonebusiness specific modules to NPM means that others can benefit from reusing your modules.