Skip to Content
Node: Up and Running
book

Node: Up and Running

by Tom Hughes-Croucher, Mike Wilson
April 2012
Intermediate to advanced
204 pages
5h 42m
English
O'Reilly Media, Inc.
Content preview from Node: Up and Running

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.

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Node.js in Practice

Node.js in Practice

Marc Harter, Alex Young
Building APIs with Node.js

Building APIs with Node.js

Caio Ribeiro Pereira

Publisher Resources

ISBN: 9781449332235Supplemental ContentErrata