Node by example

Node by example: 3. Modules

3. Modules

The complete source code can be downloaded here:

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: " +"bar"));

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


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


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():


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


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

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

Lets take a look at the foobar.js module:

var foo = 'Foo'; = function() {
  return foo;
}; = 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: " +"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:

[1] CommonJS Modules Spec: