Nodejs Modules


Node use CommonJS.

Let creates a file named main.js with the following content:

var hello = require('./hello');;

The require('./hello') is used to import the contents from another JavaScript 
file.  The initial './' indicates that the file is located in the same directory.  
Also note that we do not have to provide the file extension because '.js' is 
assumed by default.  The content of hello.js: = function() {
  console.log('Hello World');

Notice that we are assigning a property named world to an object named exports.  
The 'exports' object is available in every module, and it is returned whenever 
the require function is used to include the module.

Many Node users are overwriting the exports object directly:

module.exports = function() { ... };

This will directly cause the require function to return the assigned function.  
This is useful if we're doing object oriented programming, where each file 
exports the constructor of the class.

If the require line does not starts with './', '../', or '/' (for example, http 
or mysql), Node will look to see if there is a core module by that name.  If so, 
it return that directly.  If not, it will walk up the directory tree until it 
find the node_module folder.  If the node_module folder is found, it will look 
inside this folder for the file mysql.js.  If no matchin file is found, and the 
root directory (/) is reached, Node will give up and throw an exception.

Node also let us create an 'index.js' file, which indicates the main include 
file for a directory.  If we call require('./foo'), both foo.js file as well as 
the foo/index.js will be considered.  This goes for non-relative includes as 
well (such as mysql).
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License