Nov 10, 2012

Node.js: exports vs module.exports

Posted Nov 10, 2012
If you've been using node.js, you're probably familiar with the following scenario:

book.js:
exports.title = 'The Alchemist'

reader.js:
var book = require('./book');
console.log(book.title); // prints "The Alchemist" to console

In the above, "exports" allows us to call the property "title" of book.js. However, this approach always requires us to define and call a method or property. The object returned by "require('./book')" is the exports object which is created by the node.js framework but what if we want our own custom object returned?


This when "module.exports" becomes useful:

book.js:
module.exports = 'The Alchemist';

reader.js:
var book = require('./book');
console.log(book); // prints "The Alchemist" to console

In the above, notice that we don't need to call any method of book to be able to use it. In some cases, module.exports may be more convenient. In Express js, I use this approach to modularize my routes.

1 comment: