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 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:
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 logFormatterModule.info() or logFormatterModule.warning() or logFormatterModule.error().