Node by example

Node by example: 3. Modules

3. Modules

The complete source code can be downloaded here: http://github.com/Hendrik/node-by-example

As mentioned in the previous chapter, you use

var some_var = require("built-in_module_name");

to include one of Node.JS's built-in modules.

What if you want to include your own module?
Node.JS uses the CommonJS module system [1], so that it is easy to add your own modules to your script.

Lets start with the script that is going to include our module, modules.js:

var foobar = require("./foobar"),
      sys = require("sys");

sys.puts("Foobar: " + foobar.bar("bar"));

If you include a built-in module, then you use

require("module_name");

but if you wish to use a custom module named "module_name.js", then you use

require("./module_name");

Please note: the ".js" is omitted.
./ indicates the directory relative to the file calling require().
This would change to the following, if your module was located in the "libs" subdirectory relative to the file calling require():

require("./libs/module_name");

Alternatively you can also provide the full path to the module:

require("/path/to/module_name");

The next line outputs "Foobar: " plus some output taken from the foobar.js module:

sys.puts("Foobar: " + foobar.bar("bar"));

Lets take a look at the foobar.js module:

var foo = 'Foo';

exports.foo = function() {
  return foo;
};

exports.bar = function(bar) {
  return foo + bar;
};

Any variable defined in a module is private, so its scope is limited to the module.
In this case the local variable "foo" is private to foobar.js

var foo = 'Foo';

foobar.js has exported 2 functions foo() and bar(), which you can then use in the file calling require() for the module.

modules.js used:

sys.puts("Foobar: " + foobar.bar("bar"));

so it calls the bar() function of the foobar.js module passing "bar" as a string to it.
The result is the "Foobar" output.

More information on the Node.JS module system: http://nodejs.org/api.html#_modules


[1] CommonJS Modules Spec: http://commonjs.org/specs/modules/1.0/