The first time I went about creating a node module I was confused how I would tell node which object to return. Creating modules in node is incredibly simple. Yet the difference between module.exports and exports is confusing. Some npm packages use the exports variable while some use module.exports to return the module object.

So to clear things up for myself and for any reader who is just as confused as I was, here is the difference:

module.exports

When you require a module:

var app = require('module');

Node returns the ‘module.exports’ object. You can console.log(module) to see the exports object paramater.

exports

‘exports’ by itself is just a global variable provided to you for convenience. Initially, the global ‘exports’ variable references the same memory location as module.exports.

So if you assign ‘exports’ :

exports = //your module object

You are changing the object exports. Javascript does not pass by reference at all. There is no way to pass the whole object in javascript because variables dont hold objects, they hold the values of the references to those objects. That is the value of the address of the object.

So if I do this:

exports.a = //your module object

Then require will work:

var app = require('module');
console.log(app.a)//prints the contents of exports.a and not 'undefined'

The ‘.’ operator dereferences the object and adds an ‘a’ property.

Best practice

So that is the only way I can return my module using exports ‘provided I do not use module.exports anywhere in the code’. It is easy to remember the difference if you understand it.

However, the best and most common practice right now seems to be:

module.exports = exports = //your module object

OR just using module.exports.