Notes of a Pragmatic Geek

by Daniel Khan

node.js – how exports and module.exports works

When starting with node.js the way modules work seems a little awkward.

Especially the difference between exports and module.exports causes much confusion.
Somehow we tend to think that exports is the global/important variable and module.exports is something local to the module and has less importance.

Consequently people do not understand why they have to use module.exports when they want to expose an object as a whole to do something like this: require(‘wizzard’).doMagic() - this can only be done if the return of the include is an instance of an object.

The answer is quite simple:

exports is just a shortcut for module.exports. It is created by node.js when creating a new module.

Node simply does a var exports = module.exports. After that exports points to that property inside module.
We can easily add other properties to it by using exports.myProperty = ‘some value’.
But if you try to set the whole exports to a variable (no matter what it holds – it can also be a literal like ’42’) you overwrite the reference from exports to module.exports and the module will export nothing.

The example below shows right and wrong ways to export and the output after requiring the module and logging it to console.

Let’s visualize this:


That’s it. Feel free to comment and ask questions.

Leave a Reply

Your email address will not be published. Required fields are marked *