-
Book Overview & Buying
-
Table Of Contents
Node Web Development - Second Edition
By :
Modules are the basic building blocks for constructing Node applications. A Node module encapsulates functions, hiding details inside a well protected container, and exposing an explicitly declared list of functions.
We have already seen modules in action; every JavaScript file we use in Node is itself a module. It's time to see what they are and how they work.
In the ls.js example in Chapter 2, Setting up Node, we wrote the following code to pull in the fs module, giving us access to its functions:
var fs = require('fs');The require function searches for modules, and loads the module definition into the Node runtime, making its functions available. The fs object (in this case) contains the code (and data) exported by the fs module.
Let's look at a brief example of this before we start diving into the details. Ponder over this module, simple.js:
var count = 0;
exports.next = function() { return count++; }This defines an exported function and a local variable. Now let's use it...
Change the font size
Change margin width
Change background colour