Local Modules

Unlike built-in and external modules, local modules are created locally in your Node.js application. Let’s create a simple calculating module that calculates various operations. Create a calc.js file that has the following code: 

JavaScript
// Filename: calc.js 

exports.add = function (x, y) {
    return x + y;
};

exports.sub = function (x, y) {
    return x - y;
};

exports.mult = function (x, y) {
    return x * y;
};

exports.div = function (x, y) {
    return x / y;
};

Since this file provides attributes to the outer world via exports, another file can use its exported functionality using the require() function. 

javascript
// Filename: index.js 

const calculator = require('./calc');

let x = 50, y = 10;

console.log("Addition of 50 and 10 is "
             + calculator.add(x, y));

console.log("Subtraction of 50 and 10 is "
             + calculator.sub(x, y));

console.log("Multiplication of 50 and 10 is "
             + calculator.mult(x, y));

console.log("Division of 50 and 10 is "
             + calculator.div(x, y));

Step to run this program: Run the index.js file using the following command:

node index.js

Output:

Addition of 50 and 10 is 60
Subtraction of 50 and 10 is 40
Multiplication of 50 and 10 is 500
Division of 50 and 10 is 5

Note: This module also hides functionality that is not needed outside of the module.

Node.js Modules

In Node.js, Modules are the blocks of encapsulated code that communicate with an external application on the basis of their related functionality. Modules can be a single file or a collection of multiple files/folders. The reason programmers are heavily reliant on modules is because of their reusability as well as the ability to break down a complex piece of code into manageable chunks. 

We will discuss the different types of Node.js Modules:

Table of Content

  • Core Modules
  • Local Modules
  • Third-party modules

Similar Reads

Core Modules

Node.js has many built-in modules that are part of the platform and come with Node.js installation. These modules can be loaded into the program by using the required function....

Local Modules

Unlike built-in and external modules, local modules are created locally in your Node.js application. Let’s create a simple calculating module that calculates various operations. Create a calc.js file that has the following code:...

Third-party modules

Third-party modules are modules that are available online using the Node Package Manager(NPM). These modules can be installed in the project folder or globally. Some of the popular third-party modules are Mongoose, express, angular, and React....