Friday, 3 June 2016

Node Require and Exports

A module encapsulates related code into a single unit of code. When creating a module, this can be interpreted as moving all related functions into a file.

---misc.js------
var x = 5;
var addX = function(value) {
  return value + x;
};

Now, before we look at how to expose things out of a module, let's look at loading a module. This is where require comes in. require is used to load a module, which is why its return value is typically assigned to a variable:

var misc = require('./misc');

as long as our module doesn't expose anything, the above isn't very useful. To expose things we use module.exports and export everything we want:

---misc.js------
var x = 5;
var addX = function(value) {
  return value + x;
};
module.exports.x = x;
module.exports.addX = addX;

--usage--
var misc = require('./misc');
console.log("Adding %d to 10 gives us %d", misc.x, misc.addX(10));


There's another way to expose things in a module:

var User = function(name, email) {
  this.name = name;
  this.email = email;
};
module.exports = User;

the last thing to consider is what happens when you directly export a function:

var powerLevel = function(level) {
  return level > 9000 ? "it's over 9000!!!" : level;
};
module.exports = powerLevel;
When you require the above file, the returned value is the actual function. This means that you can do:

require('./powerlevel')(9050);
Which is really just a condensed version of:

var powerLevel = require('./powerlevel')
powerLevel(9050);
Hope that helps!

No comments:

Post a Comment