Learn about Node Modules in Node.js*

ID 659922
Updated 4/26/2016
Version Latest
Public

author-image

By

In continuation to the article Introduction to node.js this article focuses on node.js modules.

WHAT IS A NODE MODULE?

A module encapsulates related code into a single unit of code. When creating a module, this can be interpreted as moving all related functions into a file. Node modules run in their own scope so that they do not conflict with other modules. Node relatedly provides access to some globals to help facilitate module interoperability. The primary 2 items that we are concerned with here are require and exports. You require other modules that you wish to use in your code and your module exports anything that should be exposed publicly. Lets see an example : save the below code as testcode.js

exports.name = function() {
    console.log('My name is Sourav Lahoti');
};

which you call from another file thus:

var testCode= require('./testcode.js');
testCode.name(); // 'My name is Sourav Lahoti

So in this example we see we use exports keyword to define a module that would be imported by another js file as in case of test.

DIFFERENCE BETWEEN module.exports and exports

You can use both exports and module.exports to import code into your application like this:

var mytestcode = require('./path/to/mycode');

The basic use case you'll see (e.g. in ExpressJS example code) is that you set properties on the exports object in a .js file that you then import using require()

So in a simple counting example, you could have: count.js

var counter = 1;

exports.increment = function() {
    counter++;
};

exports.getCountNumber = function() {
    return counter;
};

.. then in your application (any other .js file):

var count = require('./count.js');
console.log(counting.getCountNumber()); // 1
count.increment();
console.log(counting.getCountNumber()); // 2

In simple terms, you can think of required files as functions that return a single object, and you can add properties (strings, numbers, arrays, functions, anything) to the object that's returned by setting them on exports.

Sometimes you'll want the object returned from a require() call to be a function you can call, rather than just an object with properties. In that case you need to also set module.exports, like this:

(hello.js):

module.exports = exports = function() {
    console.log("Hello World!");
};

(app.js):

var Hello = require('./hello.js');
Hello(); // "Hello World!"

So we have touch about node modules and how it is used in node.js . In next article we will touch upon npm ( node package manager and why is it used for ).