Cogs and Levers A blog full of technical stuff

node.js module patterns

In today’s post, I’ll walk through some of the more common node.js module patterns that you can use when writing modules.

Exporting a function

Exporting a function from your module is a very procedural way to go about things. This allows you to treat your loaded module as a function itself.

You would define your function in your module like so:

module.exports = function (name) {
  console.log('Hello, ' + name);
};

You can then use your module as if it were a function:

var greeter = require('./greeter');
greeter('John');

Exporting an object

Next up, you can pre-assemble an object and export it as the module itself.

var Greeter = function () { };

Greeter.prototype.greet = function (name) {
  console.log('Hello, ' + name);
}

module.exports = new Greeter();

You can now start to interact with your module as if it were an object:

var greeter = require('./greeter');
greeter.greet('John');

Exporting a prototype

Finally, you can export an object definition (or prototype) as the module itself.

var Greeter = function () { };

Greeter.prototype.greet = function (name) {
  console.log('Hello, ' + name);
}

module.exports = Greeter;

You can now create instances from this module:

var Greeter = require('./greeter');
var greeter = new Greeter();
greeter.greet('John');