Saturday, 11 November 2017

Node.js | Node.js Local Module

Local modules are modules created locally in Node.js application. These modules may include different functionalities of the application in separate files and folders. We can also package it and distribute it via NPM, so that Node.js community can use it.

For example, if we need to connect to MongoDB and fetch data then we can create a module for it, which can be reused in our application.

Writing a Local Module:
Let's write logging module which logs the information, warning or error to the console.

In Node.js, the module should be placed in a separate JavaScript file. So, create a LogFormatter.js file with below code in it.

<!--Step:1 Create an Object with three required methods -->
var log_formatter = {
            info: function (info) {
                console.log('Info: ' + info);
            warning: function (warning) {
                console.log('Warning: ' + warning);
            error: function (error) {
                console.log('Error: ' + error);

<!--Step:2 Assign the object to module.exports -->
module.exports = log_formatter

In the above Local module, two major steps are there:

1. We have created an object with three functions,
             info(), warning() and error().

2. We have assigned this object to module.exports. The module.exports exposes a log_formatter 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.

Loading Local Module:
To use local modules in the application, we need to load it using require() function in the same way as we used for the core modules. However, we need to specify the path of JavaScript file of the module.


var logFormatterModule = require('./LogFormatter.js');'Node.js started');
logFormatterModule.error('Node.js error);

First, it loads the logging module using require() function and specified path where logging module is stored. Logging module is contained in LogFomatter.js file in the root folder. So, we have specified the path './LogFormatter.js' in the require() function. The '.' denotes a root folder.

The require() function returns a log_formatter object because logging module exposes an object in LogFormatter.js using module.exports. Now we can use logging module as an object and call any of its function like or logFormatterModule.warning() or logFormatterModule.error().

D:\node>node TestLogFormatter.js
Info: Node.js started
Error: Node.js error

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...