CommonJs Modules


I explain CommonJs modules by means of a simple example on this page. There is also a very technical specification: CommonJs Modules/1.1.

Every file is a module living in its own top-level scope. No special syntax needed. Any function or property, which you attach to exports in your module, will be exposed and can be imported by other modules.

Anatomy of a Module

Every JavaScript file is treated as a module. A simple module in the file “foobar.js” might look like the following. I want to expose the function add but not the private adder:

      // in foobar.js
      //
      var adder = function(a, b) {
          return a + b;
      };
      exports.add = function(a, b) {
          return adder(a, b);
      };

You can require('./foobar') and access add as foobar.add:

      >> var foobar = require('./foobar');
      >> foobar.add(3,4)
      7

But you can not access the private adder function:

      >> foobar.adder(2,2)
      ReferenceError