Posted by & filed under Node.js.

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.

Thomas Hunter II

Thomas is passionate about technology and building products. A web design business created while attending college slowly evolved into a brick and mortar on Main St. of his small Midwestern hometown. His desire for fame and fortune led to the co-founding of a Y Combinator startup and a life in California.

Tags:

Hey there! I'm currently writing a book on Microservices which I expect to release in early 2017. If you're interested in getting updates please signup here. More info about the Book