NodeJS modules are the set of functions bundled together into single or multiple javascript files, which perform a particular task and represents various functionalities. It has a unique context, thus, it never interfere nor pollute the scope of other modules. NodeJS modules enable the code reusability and enhance the ease of usage. NodeJS modules includes three different types of modules-
As NodeJS is a very lightweight framework so, the core modules bundle the absolute minimum functionalities. NodeJS has a various built-in modules which you can use without any further installation, which are given below-
Module | Description |
---|---|
http | It includes classes, methods, and events required to create NodeJS HTTP server. |
url | It includes methods for URL resolution and parsing. |
querystring | It includes methods to deal with a query string. |
path | It includes methods to deal with file paths. |
fs | It includes classes, methods, and events to work with file I/O. |
util | It includes utility functions, which can be useful for programmers. |
Core module can be easily loaded using below code-
const module = require('module_name');
The local modules of NodeJS are custom modules which are created locally by the developer. These modules can include various functionalities of application, which can be bundled into separate files and folders. Local modules can be easily distributed to the NodeJS community using NPM (Node Package Manager).
After creation, a local Modules can be easily loaded like core modules. Let show it, using a basic example-
// Create your custom or local module file.
const detail = {
name: function (name) {
console.log('Name: ' + name);
},
address: function (address) {
console.log('Address: ' + address);
}
};
module.exports = detail;
// To use this, include it in your main application file.
const myLocalModule = require('./local.module.js');
myLocalModule.name('Tutorials Logic');
myLocalModule.address('Bangalore, IN');
npm install --g module_name // To install it globally
npm install --save module_name // To install it locally in your application