Defining a module
Modules are the basic building block for constructing Node.js applications. A Node.js 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 in the previous chapter. Every JavaScript file we use in Node.js 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.js, 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, loading the module definition into the Node.js runtime, and makes its functions available. In this case, the fs
object contains the code (and data) exported by the fs
module.
This is true of every Node.js module, the exports
object within the module is the interface provided to other code. Anything assigned to a field of the exports
object is available to other pieces of code, and...