NodeJS Modules

Modules

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-

Core/Built-in Modules.

Core/Built-in Modules. Local Modules.

Local Modules. Third Party Modules.

Core/Built-in 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-

example const module = require('module_name');

Local Modules

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-

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');

Third Party or External Modules