Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.
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.