Show Buttons
Share On Facebook
Share On Twitter
Share On Google Plus
Share On Linkdin
Share On Reddit
Share On Stumbleupon
Contact us
Hide Buttons

Understanding nodejs module exports and require

Nodejs allows you to write mod­u­lar code by divid­ing your busi­ness logic into sin­gle pur­pose files called mod­ules. When you are new to nodejs, it can some­times be dif­fi­cult to under­stand what is hap­pen­ing and how things are connected.

Con­sider the fol­low­ing lines of code in a file called add.js in my project root.

function add(x,y){
    return x+y;
}

We can con­vert this file into a mod­ule that can be used in a nodejs application.

function add(x,y){
    return x+y;
}

module.exports = add;

The only dif­fer­ence in the two ver­sions of the add.js file is the last line.
First lets see how this could nor­mally be used as a nodejs mod­ule from another file in my root direc­tory, say index.js.

var adder = require('./add.js');

console.log(adder(1,100));

This is prob­a­bly the sim­plest exam­ple of how a nodejs mod­ule is defined and used. Now lets try to under­stand the con­cepts behind how the pieces are connected.

In your index.js file, when you say require('./add.js'), node searches for a file called add.js in the cur­renty direc­tory. Then, this file is loaded and loaded just once. i.e. a call to require the same file — add.js from either index.js or any other file will not cause the file to be loaded again.(This is why you need to restart your nodejs server every­time you make changes to your mod­ules since they are not auto­mat­i­cally reloaded on change).

When the file add.js is loaded, every­thing inside of it is wrapped inside a clo­sure. This means that any local vari­ables declared in your files using the var key­word will not be vis­i­ble out­side the file. Since we defined an add func­tion within our file that we want other files to be able to use, we def­i­nitely want it to be exposed. The only way to expose any local vari­ables or func­tions is by set­ting the value of the module.exports.

You might won­der, what the hell is module.exports. Isint that sup­posed to cause a javascript error since its not defined any­where in sight?

Appar­ently, when nodejs loads a file as a mod­ule, it is pro­vided this file with some vari­ables as listed in the docs here

Think about your add.js file to be con­verted to some­thing like this in memory.

(function(module,__dirname, process){ //... and other global variables
    function add(x,y){
    return x+y;
}

module.exports = add;
}(module, directoryName, processDetails));

Now you can clearly see the clo­sure and the mod­ule vari­able. The mod­ule vari­able has a spe­cial prop­erty called the exports which is the value that is returned by a require call. So, if you set it to an object, the require call for this mod­ule will result in that object (e.g. use­ful for con­fig­u­ra­tion objects). If you set it to a func­tion, the require call returns that func­tion, as seen in our example.

NOTE: A lot of times peo­ple also use ‘exports’ dire­cly as a short­hand instead of writ­ing ‘module.exports’ since exports also one of the global vari­ables passed into the clo­sure. Although exports is essen­tially same as module.exports, reas­sign­ing exports to a new object does not reas­sign module.exports to the new object and can cause con­fu­sion if you’re not care­ful about what you are doing. My rec­om­men­da­tion, avoid the pain and just use module.exports because stay­ing sane is more impor­tant than code brevity.

Lets just rein­force the con­cept of nodejs mod­ules with another sim­ple exam­ple. This time, we will export an object instead of a func­tion from our new file — utils.js

function add(){
    return x+y;
}

function subtract(){
    return x-y;
}

module.exports = {
  add: add,
  sub: subtract
};

Notice that since our func­tions are defined inside the mod­ule, we were able to use a dif­fer­ent func­tion name when expos­ing the sub­tract function.

Here’s how you could use your utils.js mod­ule in your index.js file

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

console.log(utils.add(1,100));
console.log(utils.sub(100,1));

nodejs module export

I hope this post has helped you get a bet­ter under­stand­ing of why you need write a module.exports at the end of a nodejs mod­ule and why it actu­ally works.

  • Man­preet Gill

    how to call­back return in main.js file

    this file is example.js:=

    module.exports = {

    dash­board­dis­tance: function(a, b, c, d, callback) {

    var ds = 0;

    var dis­tance = require(‘google-distance’);

    distance.get({

    index: 1,

    ori­gin: a + ‘,’ + b,

    des­ti­na­tion: c + ‘,’ + d

    }, function(err, data) {

    if (err) {

    console.log(“a”);

    ds = 0;

    return callback(err, ds);

    } else {

    console.log(“b”);

    ds = data.distance;

    return callback(null, ds);

    }

    });

    },

    };

    main.js file this :=

    var exam­ple = require(‘./example.js’);

    example.dashboarddistance(a, b, c, d, function(err, distance) {

    if (err) {

    // dosome­thing and return

    return ;

    }

    console.log(distance);

    });

  • Man­preet Gill

    how to call­back return in main.js file