Database Reference
In-Depth Information
NPM provides a facility called shrinkwrap that works similarly to the
Gemfile.lock file in Ruby gems to specify specific versions of the
packages.
Now, everything is ready to begin developing a node.js web application.
Adding Modules to a Project
Any nontrivial project should break down code into manageable modules
to improve maintainability. In Node, this is done via modules that are
implemented as simple JavaScript files and imported using the require
statement. Unlike some languages, such as Java, there is no requirement
that modules be located in any particular directory, though it is usually best
to place them in a subdirectory to differentiate them from the main files
used to run servers and other applications.
Modules can work two ways, exporting specific functions or exporting the
entire module as a function. Some modules, such as the connect module
used later in this chapter, use both methods. To export a function from a
module, add that function to the exports block implicitly available inside
a module:
function notExported() {
console.log("This function can only be used
internally");
}
exports.exported = function() {
console.log("This can be called externally");
}
exports.callInternal = function() {
notExported();
}
If these functions are in a file called lib/module.js , they can be imported
and used via the require function:
var mod = require('./lib/module.js');
mod.exported();
// Prints "This can be called externally"
mod.callInternal();
Search WWH ::




Custom Search