Building a Really Simple Node.js Module

This is an example of building a simple Node.js module. The code is super simple, but it should give you a good feel for how it is done. The magic of the Node.js module system is performed mostly by the require function, which is similar to PHP's include/require statements.

When you perform a require, Node.js looks for a file in a few different locations. They all have their purposes, but for this demo, we'll be using the node_modules subdirectory. Simply create this directory in the same directory as your main application code. Then, inside of the node_modules directory, add another subdirectory, but this time it will be named after your module. For this example I just use the phrase test.

Node.js Module Structure
Node.js Module Structure

(PS, you can ignore the package.json files, they are used for some more advanced magic).

Now that you have the necessary files in place, we need some code to put inside of them. The following example is really simple, but it's a good start:

app.js

var greeter = require('test');

greeter.hello("Monkey");
greeter.bye("Steven");

node_modules/test/index.js

module.exports = {
  hello: function(name) {
    console.log("Hello, " + name);
  },
  bye: function(name) {
    console.log("Goodbye, " + name);
  }
};

Example output

$ node app.js
Hello, Monkey
Goodbye, Steven

Simple, huh?

Node provides the aptly named module object for your module to work with. What you want to do is assign your object to it's exports attribute. Once you do that, this object is now returned to your calling app as the result of the require function.

Tags: #nodejs
Thomas Hunter II Avatar

Thomas has contributed to dozens of enterprise Node.js services and has worked for a company dedicated to securing Node.js. He has spoken at several conferences on Node.js and JavaScript, published a book on microservices, and is an organizer of Nodeschool SF.