Learning Node.js Part 2 – “module.exports” and “exports”

By | January 30, 2014

In my previous post, I explained the basics of loading files/modules in Node.js. In this post, I’ll explain how to work with the return data. Specifically, I will describe what you get when you call something like var math = require('./math').

First, let’s talk about how to return data in a module. There are two ways to do it:

1) exports = data (where data is what you want to return)
2) module.exports = data

What’s the difference? Nothing actually. In fact, the exports variable is simply a reference, or alias, to module.exports. This means that you could use either one, though you’ll typically see module.exports. As the documentation suggests:

As a guideline, if the relationship between exports and module.exports seems like magic to you, ignore exports and only use module.exports.

You’ll also want to notice that you set the data instead of returning it. If you’ve used PHP before, then you may be used to including files and returning the data at the end by calling return $data. In Node.js, however, you just set the variable module.exports = data and it will return it for you.

The cool thing about this syntax is that you can return the data in numerous ways.

For example, if you just need some variables/functions:

// File: math.js
module.exports.double = function(n) { return n*2; };
// File: test.js
math = require('./math');

Or if you need a a full class instance:

// File: math.js
var Math = function() {
  this.double = function(n) { return n*2; };
module.exports = new Math;
// File: test.js
var apple = require('./apple');

Or if you’re really cool and just want to export a function directly:

// File: double.js
module.exports = function(n) {
  return n*2;
// File: test.js
var double = require('./double');

// you could also use this shorthand notation for functions:

Of course, you can always return basic elements as well: a string, number, array, json object, etc. It really depends on what you need, though typically you’ll find that modules are best for classes/class instances. Anything simpler probably doesn’t belong in a module.

So there you have it. You now understand how loading modules work, and you know how to process and return data in those modules. It’s such a simple concept, but it was a little difficult for me to comprehend when I jumped directly into the code via tutorials.

Hope this helps! As always, feel free to ask questions if you have any.

Leave a Reply

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