Difference of module.exports and exports in node.js

Date: 2013-05-06

If you are new in node.js, you may get confused by the difference of module.exports and exports in node.js's module system.

Docs

Following 2 pages in official documents didn't explain them very well:

Globals Modules

Conclusion

Let me give you the conclusion first:

module.exports is the real object that been used

exports is just a reference

Details

Then let's explain them in details:

in Javascript, when you use = to assign an object to a variable, it's passed it's reference, not value so:

 var a = {name:'a'};
 var b = a;
 b.name = 'b';
 console.log(a.name); // this will output 'b'

in node.js, for each module, there is a module object been automaticlly created. and in this module object, an exports attribute been automatically created too, and assigned a initial value: {}, so in code, it look like this:

module.exports = {};

and then, Nodejs added a convinient way to use this module.exports object

var exports = module.exports;

So that when you want to add a attribute into module.exports object, you can do it like this:

exports.test = function(){
    //do something;
}

What if i want to assign the whole exports object as a function? so you may try it like this way:

exports = function(){
    //do something
}

This will not work. because when you do this, the exports variable is been assigned to another object (a function), and it's now not the same object as module.exports, you can add following code to check it

module.exports === exports // will return false

and as I mentioned before: module.exports is the real object that been used

so when you want to do make the whole module just been a function. do it like this:

module.exports = function(){
    //do something    
};