File Modules

If the exact filename is not found, then Node.js will attempt to load the required filename with the added extensions: .js, .json, and finally .node.

.js files are interpreted as JavaScript text files, and .json files are parsed as JSON text files. .node files are interpreted as compiled addon modules loaded with process.dlopen().

A required module prefixed with ‘/’ is an absolute path to the file. For example, require(‘/home/marco/foo.js’) will load the file at /home/marco/foo.js.

A required module prefixed with ‘./’ is relative to the file calling require(). That is, circle.js must be in the same directory as foo.js for require(‘./circle’) to find it.

Without a leading ‘/’, ‘./’, or ‘../’ to indicate a file, the module must either be a core module or is loaded from a node_modules folder.

If the given path does not exist, require() will throw an Error with its code property set to ‘MODULE_NOT_FOUND’.

Folders as Modules

It is convenient to organize programs and libraries into self-contained directories, and then provide a single entry point to that library. There are three ways in which a folder may be passed to require() as an argument.

The first is to create a package.json file in the root of the folder, which specifies a main module. An example package.json file might look like this:

{ “name” : “some-library”,

“main” : “./lib/some-library.js” }

If this was in a folder at ./some-library, then require(‘./some-library’) would attempt to load ./some-library/lib/some-library.js.

This is the extent of Node.js’s awareness of package.json files.

If there is no package.json file present in the directory, or if the ‘main’ entry is missing or cannot be resolved, then Node.js will attempt to load an index.js or index.node file out of that directory. For example, if there was no package.json file in the above example, then require(‘./some-library’) would attempt to load:

  • ./some-library/index.js
  • ./some-library/index.node

If these attempts fail, then Node.js will report the entire module as missing with the default error:

Error: Cannot find module ‘some-library’

Loading from `node_modules` Folders

If the module identifier passed to require() is not a core module, and does not begin with ‘/’, ‘../’, or ‘./’, then Node.js starts at the parent directory of the current module, and adds /node_modules, and attempts to load the module from that location. Node.js will not append node_modules to a path already ending in node_modules.

If it is not found there, then it moves to the parent directory, and so on, until the root of the file system is reached.

For example, if the file at ‘/home/ry/projects/foo.js’ called require(‘bar.js’), then Node.js would look in the following locations, in this order:

  • /home/ry/projects/node_modules/bar.js
  • /home/ry/node_modules/bar.js
  • /home/node_modules/bar.js
  • /node_modules/bar.js

This allows programs to localize their dependencies, so that they do not clash. It is possible to require specific files or sub modules distributed with a module by including a path suffix after the module name. For instance require(‘example-module/path/to/file’) would resolve path/to/file relative to where example-module is located. The suffixed path follows the same module resolution semantics.

Loading from the global folders

If the NODE_PATH environment variable is set to a colon-delimited list of absolute paths, then Node.js will search those paths for modules if they are not found elsewhere.

On Windows, NODE_PATH is delimited by semicolons (;) instead of colons.

NODE_PATH was originally created to support loading modules from varying paths before the current module resolution algorithm was frozen.

NODE_PATH is still supported, but is less necessary now that the Node.js ecosystem has settled on a convention for locating dependent modules. Sometimes deployments that rely on NODE_PATH show surprising behavior when people are unaware that NODE_PATH must be set. Sometimes a module’s dependencies change, causing a different version (or even a different module) to be loaded as the NODE_PATH is searched.

Additionally, Node.js will search in the following list of GLOBAL_FOLDERS:

1: $HOME/.node_modules

2: $HOME/.node_libraries

3: $PREFIX/lib/node

Where $HOME is the user’s home directory, and $PREFIX is Node.js’s configured node_prefix. These are mostly for historic reasons. It is strongly encouraged to place dependencies in the local node_modules folder. These will be loaded faster, and more reliably.

Local Module

Local modules are modules created locally in your Node.js application. These modules include different functionalities of your application in separate files and folders. You can also package it and distribute it via NPM, so that Node.js community can use it. For example, if you need to connect to MongoDB and fetch data then you can create a module for it, which can be reused in your application.

Writing Simple Module

Let’s write simple logging module which logs the information, warning or error to the console.

In Node.js, module should be placed in a separate JavaScript file. So, create a Log.js file and write the following code in it.

Log.js

var log = {

info: function (info) {

console.log(‘Info: ‘ + info);

},

warning:function (warning) {

console.log(‘Warning: ‘ + warning);

},

error:function (error) {

console.log(‘Error: ‘ + error);

}

};

module.exports = log

In the above example of logging module, we have created an object with three functions – info(), warning() and error(). At the end, we have assigned this object to module.exports. The module.exports in the above example exposes a log object as a module.

The module.exports is a special object which is included in every JS file in the Node.js application by default. Use module.exports or exports to expose a function, object or variable as a module in Node.js.

Now, let’s see how to use the above logging module in our application.

Loading Local Module

To use local modules in your application, you need to load it using require() function in the same way as core module. However, you need to specify the path of JavaScript file of the module.

The following example demonstrates how to use the above logging module contained in Log.js.

app.js

var myLogModule = require(‘./Log.js’);

myLogModule.info(‘Node.js started’);

In the above example, app.js is using log module. First, it loads the logging module using require() function and specified path where logging module is stored. Logging module is contained in Log.js file in the root folder. So, we have specified the path ‘./Log.js’ in the require() function. The ‘.’ denotes a root folder.

The require() function returns a log object because logging module exposes an object in Log.js using module.exports. So now you can use logging module as an object and call any of its function using dot notation e.g myLogModule.info() or myLogModule.warning() or myLogModule.error()

Run the above example using command prompt (in Windows) as shown below.

C:\> node app.js

Info: Node.js started

Thus, you can create a local module using module.exports and use it in your application.

Share this post
[social_warfare]
Cycles
HTTP Module

Get industry recognized certification – Contact us

keyboard_arrow_up