The Wayback Machine - http://web.archive.org/web/20250111005926/https://www.geeksforgeeks.org/node-js-modules/
Open In App

Node.js Modules

Last Updated : 07 Jan, 2025
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Modules in Node.js are blocks of encapsulated code that can be reused throughout your application. These modules can include functions, objects, and variables that are exported from the code files. In this article, we’ll cover the basics of Node.js modules, the different types of modules, how to create and use them.

What are Modules in Node.js?

Modules in Node.js are like JavaScript libraries — a set of related functions that you can include in your application. Every Node.js file can be considered a module that can export code for reuse in other parts of the application. This modular approach allows developers to separate concerns, reuse code, and maintain a clean architecture.

How Node.js Modules Work?

Each module in Node.js is executed within its own module scope. This means variables, functions, and classes defined in one module are private to that module unless explicitly exported for use by other modules. This behavior avoids global namespace pollution and improves code maintainability.

At its core, a Node.js module is an object that contains the following key properties:

  • exports: The object that a module can export for use in other modules.
  • require(): A function that is used to import modules into other modules.
  • module: The object that represents the current module.

When a module is loaded, Node.js wraps the module code in a function to provide this module system.

Types of Node

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

Note: Node.js modules are key to organizing your code in manageable chunks.

1. 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.

Syntax:

const module = require('module_name');

The require() function will return a JavaScript type depending on what the particular module returns. The following example demonstrates how to use the Node.js http module to create a web server. 

JavaScript
const http = require('http');
http.createServer(function (req, res) {
    res.writeHead(200, { 'Content-Type': 'text/html' });
    res.write('Welcome to this page!');
    res.end();
}).listen(3000);


In the above example, the require() function returns an object because the Http module returns its functionality as an object. The function http.createServer() method will be executed when someone tries to access the computer on port 3000.

The res.writeHead() method is the status code where 200 means it is OK, while the second argument is an object containing the response headers. The following list contains some of the important core modules in Node.js:

Core ModulesDescription
httpcreates an HTTP server in Node.js.
assertset of assertion functions useful for testing.
fsused to handle file system.
pathincludes methods to deal with file paths.
processprovides information and control about the current Node.js process.
osprovides information about the operating system.
querystringutility used for parsing and formatting URL query strings.
urlmodule provides utilities for URL resolution and parsing.

2. 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.

3. 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. 

Example:

  • npm install express
  • npm install mongoose
  • npm install -g @angular/cli

Example: Installing and Using Express

npm install express

Create a Simple Express Server:

JavaScript
const express = require('express');
const app = express();
const port = 3000;

app.get('/', (req, res) => {
    res.send('Hello World!');
});

app.listen(port, () => {
    console.log(`Example app listening at http://localhost:${port}`);
});

Run the Server: Use this command to run the node application.

node server.js

When you navigate to http://localhost:3000 in your browser, you should see Hello World!.

Exporting and Importing Modules

Node.js allows developers to define the module’s public API by exporting functions, objects, or classes using module.exports. The code that uses the module can then import these exported entities using require().

1. Default Export:

You can export a single function or object using module.exports:

// logger.js
module.exports = function log(message) {
console.log(message);
};

2. Named Exports:

You can export multiple functions or objects by attaching them to the exports object:

// math.js
exports.add = function (a, b) {
return a + b;
};

exports.multiply = function (a, b) {
return a * b;
};

You can then import them as:

// app.js
const math = require('./math');
console.log(math.add(2, 3)); // Output: 5
console.log(math.multiply(2, 3)); // Output: 6

Module Caching in Node.js

When a module is loaded using require(), Node.js caches it. This means that subsequent require() calls for the same module will return the cached version, improving performance by avoiding repeated loading. If you modify the module after it’s been loaded, you will need to clear the cache or restart your application to see the changes.

Benefits of Using Modules in Node.js

  • Encapsulation: Modules help keep the code modular, encapsulating functionalities within distinct files. This ensures that each module only exposes what is necessary, preventing unnecessary access to internal details.
  • Reusability: Modules can be reused across different parts of your application or even in different applications, reducing code duplication and improving maintainability.
  • Maintainability: By breaking down the code into smaller, focused modules, it’s easier to manage, update, and debug applications as they grow in complexity.
  • Modularity and Separation of Concerns: Each module is responsible for a specific functionality or task. This approach supports clean code architecture by separating concerns and making the application easier to understand.


Next Article

Similar Reads

three90RightbarBannerImg