Chapter 8. Extending Node

Modules

The module system in Node makes it easy to create extensions to the platform. It is simple to learn and enables us to easily share reusable library code. The Node module system is based on the commonJS module specification. We’ve already used lots of modules in the previous chapters, but here we’ll study how to create our own modules. Example 8-1 shows one simple implementation.

Example 8-1. A simple module

exports.myMethod = function() { console.log('Method output') };
exports.property = "blue";

As you can see, writing a module is as simple as attaching properties to the exports global variable. Any script that is included with require() will return its exports object. This means that everything returned from require() is in a closure, so you can use private variables in a module that are not exposed to the main scope of the program.

Node developers have created a few conventions around modules. First, it’s typical to create factory methods for a class. Although you might also expose the class itself, factory methods give us a clean way to instantiate objects. For I/O-related classes, one of the arguments is normally a callback for either the I/O being done or one of its most common aspects. For example, http.Server has a factory method called http.createServer() that takes a callback function for the request event, the most commonly used http.Server event.

Get Node: Up and Running now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.