Open In App

How To Create Modules in NodeJS?

Last Updated : 19 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Modules are the building blocks of NodeJS code. They help you break down your project into smaller, manageable pieces, each with its own job.

To create a module, just make a JavaScript file and export what you want to share. Other files can then import and use those exports, adding that functionality to their code.

Types of Modules

NodeJS has three types of modules:

  • Built-in Modules: Provided by NodeJS (e.g., fs, http, path).
  • User-defined Modules: Custom modules created by developers.
  • Third-party Modules: Modules installed via npm (e.g., express, lodash).

Steps to Create Modules in NodeJS

To create modules in NodeJS, write functions, objects, or classes in a separate file and use module.exports to export them. Import these modules in other files using the require() function for reuse.

Step 1: Creating a Module

To create a module, you simply need to write code in a separate file. You can then export specific variables, functions, or objects from that file to be used in other parts of your application.

Let’s start by creating a simple module that performs some basic mathematical operations.

File name: calc.js

javascript
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;
};
  • The calc.js file defines four functions: add, sub, mult, and div.
  • These functions are exported as properties of the module.exports object, making them accessible to other files.

Step 2: Using a Module

Now that we’ve created a module, we can import it into another file and use the exported functions.

File name: App.js

javascript
const calculator = require('./calc');
let x = 50, y = 20;
console.log("Addition of 50 and 20 is "
    + calculator.add(x, y));
console.log("Subtraction of 50 and 20 is "
    + calculator.sub(x, y));
console.log("Multiplication of 50 and 20 is "
    + calculator.mult(x, y));
console.log("Division of 50 and 20 is "
    + calculator.div(x, y));
  • The app.js file imports the calc.js module using require(‘./calc’).
  • It then uses the imported calculator object to perform arithmetic operations and logs the results.

Output

Create Module - output

Create Modules in NodeJS

Best Practices of Creating Modules in NodeJS

  • Use meaningful and descriptive names for your module files.
  • Keep your modules focused on a single responsibility (SRP).
  • Avoid global variables in your modules.


Next Article

Similar Reads