I am Hack Sparrow
Captain of the Internets.

How to write Node.js Modules

So you have come to the stage where you feel the need to write Node.js modules of your own, or maybe you are just ... curious? Whatever be your reason, in this tutorial, I will show you how to create Node.js modules.

Node.js modules are CommonJS-compliant modules, and are pretty straightforward to implement. You would have created a few modules by the end of this tutorial, trust me.

First let's see how a Node module installed via NPM is used in an app.

var easyimg = require('easyimage');

The methods and properties defined in the easyimage module are now available in the easyimg instance. You can do stuff like easyimg.resize(), easyimg.crop() etc. Quite handy for modularization, right? Time to find out how to create one for yourself.

Create a new directory called 'modtest', and cd into it:

$ mkdir modtest
$ cd modtest

Create a file named 'converter.js', which will be your module:

$ vi converter.js

The converter module will have two methods, one for converting input to binary, another for converting to hexadecimal. Content for 'converter.js':

exports.bin = function(input) {
    return input.toString(2);

exports.hex = function(input) {
    return input.toString(16);

Create another file named 'app.js', which will be your Node app:

$ vi app.js

Content for 'app.js':

var converter = require('./converter.js');

var num = 10;

var bin = converter.bin(num);
console.log('BIN:' + bin);

var hex = converter.hex(num);
console.log('HEX: ' + hex);

Run the app:

$ node app.js
BIN: 1010
HEX: a

There you have it. Your own module!

From the above example you can seen that any file with properties attached to exports can be included in any app as a valid module. However, we are having to specify the path of the module file. Not that cool, right? Why can't we do it like this?

var converter = require('converter');

We can, of course, but we will need to convert the module to a proper NPM package and install it from the local path. The process is easy, but requires some changes. Let's make our module a little neater.

Create a directory named 'converter', rename 'converter.js' to 'index.js', and move it to the 'converter' directory:

$ mkdir converter
$ mv converter.js converter/index.js

Create a package definition file for the module in the 'converter' directory:

$ cd converter
$ vi package.json

The content for 'package.json':

"name": "converter",
"version": "0.0.1",
"private": true

Create a README file for the package else NPM will complain:

$ echo Converts stuff to BIN and HEX! > README.md

Now, you are all set to create the NPM package, execute the pack command in the directory:

$ npm pack

There you go! The NPM package for our module is ready. cd back to 'modtest' directory and install the module from the 'converter' directory:

$ cd ..
$ npm install converter/converter-0.0.1.tgz
converter@0.0.1 ../node_modules/converter

Now you should be able to do this:

var converter = require('converter.js');

var bin = converter.binary(1337);

Great success! You have created a local Node module and installed it on your system using NPM. What could be the next step now?

How about publishing your trailblazing Node module online so others could install it, use it, and be totally overwhelmed by its awesomeness? Here is how to publish a Node module on the NPM registry.

This is not the end of the tutorial yet. 🙂

Creating a Node module is not just about attaching properties to the exports object, and including the module file in your apps. It is a little deeper than that, I will now explain how modules gain their powers.

There are two methods for defining the functionality of a Node module:

1. Attachment

In this method, we attach functions and properties to exports object. The exports is available by default, you don't have to define it. In our example we used the attachment method to create the 'converter' module.

exports.bin = function(input) {
return input.toString(2);

exports.hex = function(input) {
return input.toString(16);

If you need to call one of the module methods from within the module, it helps to create a local variable and assign the attached properties to it:

var bin = exports.bin = function(input) {
return input.toString(2);

Now you can call the method as bin() instead of exports.bin() from the module file.

Don't make the mistake of doing this:

bin = exports.bin = function() ...

or this:

exports.bin = bin = function() ...

The bin variable spill out into the global namespace! If you want to know more about global variables and the global namespace in Node.js, you will like Global Variables in Node.js.

2. Assignment

In this method we assign a JavaScript object to module.exports, which also is available by default in any included file. Here is an example of a module created using the assignment method:

File: pi.js

module.exports = 22/7;

File: app.js

var PI = require('./pi');

Notice how you can omit the '.js' extension of the file name of the module. Now when you execute app.js:

$ node app.js

Notice how the module is the value of Pi, instead of being an object with methods and properties. Using the assignment method your module can be any valid JavaScript object - Boolean, undefined, Number, Function etc.

One popular way of using the assignment method is to return a JavaScript function which can be used as a class:

File: pokemon.js

module.exports = function(name, age) {

this.name = name;
this.age = age;
this.get_name = function() {
return this.name;
this.get_age = function() {
return this.age;

File: app.js

var Pokemon = require('./pokemon');
var pokemon = new Pokemon('Piakchu', 99);

// OCD
var age = pokemon.get_age();
console.log(pokemon.get_name() + ' is ' + age + ' year' + (age == 1? '': 's') + ' old');

You will be able to make the best use of the assignment method if your JavaScript knowledge and skill is somewhere near the expert level, so make sure to dedicate enough time in learning more JavaScript, if you haven't already.

So which is the better of the two methods of defining a Node.js module? It really depends on what you want from your module, and how much JavaScript you know. To be a good Node.js developer, you really need to be a good JavaScript developer, so work on your JavaScript-Fu!

Oh, btw, you will like this post of mine on exports vs. module.exports in Node.js.

I hope you learnt everything you wanted to learn about creating Node.js modules from this tutorial. In case, I missed anything, El Capitan is always available in the comments, so ping me.

2 Responses to “How to write Node.js Modules”

  1. N.V.Prasad says:


    How could we can do http CRUD operations in Nodejs Module… is it possible Captain ?


  2. Captain says:

    Looks up REST and use a web development framework like Express (http://expressjs.com/).

Make a Comment