Wednesday, March 28, 2012

Node modules


Modules



Node has a simple module loading system. In Node, files and modules are in one-to-one correspondence. As an example, foo.js loads the module mjsunit.js.


The contents of foo.js:


include("mjsunit");
function onLoad () {
  assertEquals(1, 2);
}
The contents of mjsunit.js:


function fail (expected, found, name_opt) {
  // ...
}
function deepEquals (a, b) {
  // ...
}
exports.assertEquals = function (expected, found, name_opt) {
  if (!deepEquals(found, expected)) {
    fail(expected, found, name_opt);
  }
};
The module mjsunit has exported a function assertEquals(). mjsunit.js must be in the same directory as foo.js for include() to find it. The module path is relative to the file calling include(). The module path does not include filename extensions like .js.


include() inserts the exported objects from the specified module into the global namespace.


Because file loading does not happen instantaneously, and because Node has a policy of never blocking, the callback onLoad can be set and will notify the user when the included modules are loaded. Each file/module can have an onLoad callback.


To export an object, add to the special exports object. The functions fail and deepEquals are not exported and remain private to the module.


require() is like include() except does not polute the global namespace. It returns a namespace object. The exported objects can only be guaranteed to exist after the onLoad() callback is made. For example:


var mjsunit = require("mjsunit");
function onLoad () {
  mjsunit.assertEquals(1, 2);
}
include() and require() cannot be used after onLoad() is called. So put them at the beginning of your file.

No comments: