Paramclasses Academy - Blog

Tutorials Details

←
Post 5 of 40
→

Node.js Modules Explained: Built-In, Local and Third-Party Modules

Node.js Modules Explained: Built-In, Local and Third-Party Modules

October 29, 2026

✦ Node.js Modules Explained: Built-In, Local and Third-Party Modules

Node.js is a powerful JavaScript runtime used to develop web applications, REST APIs, backend services, and real-time applications. As a Node.js project grows, writing all the code in a single file becomes difficult to manage. This is where Node.js modules become useful.

Modules allow developers to divide an application into smaller, reusable, and organized pieces of code. Instead of writing everything in one file, you can create separate files for functions, calculations, database operations, authentication, and other features.

In this tutorial by Param Classes, you will learn what Node.js modules are, the different types of modules, how to import and export code, and how to create practical examples.

✦ What Are Modules in Node.js?

A module is a reusable block of code that performs a particular task. It can contain functions, variables, classes, or objects that other parts of an application can use.

For example, imagine you are developing a student management system. You might create separate modules for:

  • Student registration

  • Student records

  • Fee calculations

  • Database connections

  • User authentication

This structure makes your application easier to understand, test, update, and maintain.

❖ Why Are Node.js Modules Important?

Modules provide several advantages:

  1. Code reusability: Write a function once and use it in multiple files.

  2. Better organization: Keep related functions and features together.

  3. Easy maintenance: Update one module without unnecessarily changing the entire application.

  4. Team collaboration: Different developers can work on separate modules.

  5. Simpler testing: Individual modules can be tested independently.

  6. Reduced duplication: Avoid repeating the same code in different places.

✦ Types of Modules in Node.js

Node.js modules are commonly grouped into three categories.

❖ 1. Built-In Modules

Built-in modules are provided by Node.js. You do not need to install them separately using npm.

Some commonly used built-in modules include:

Module Purpose
fs Read and write files
path Work with file and directory paths
http Create HTTP servers
os Access operating system information
events Work with events and event listeners
crypto Perform cryptographic operations

 

 

For example, the path module helps developers work with file paths across different operating systems.

Example: Using the Built-In path Module

Create a file named app.js:

const path = require('path');

const fileName = 'student.txt';

console.log('File name:', path.basename(fileName));
console.log('Extension:', path.extname(fileName));
console.log('Directory:', path.dirname('/project/files/student.txt'));

Expected output:

File name: student.txt
Extension: .txt
Directory: /project/files

Here, require('path') loads the built-in path module. Its methods help extract information from file paths.

❖ 2. Local Modules

Local modules are created by you inside your own project. They allow you to move reusable functions or application logic into separate files.

Suppose you want to calculate the total fee for a student. Instead of writing the calculation in every file, create a dedicated module.

Step 1: Create fee.js

function calculateFee(courseFee, admissionFee) {
    return courseFee + admissionFee;
}

module.exports = calculateFee;

The module.exports statement makes the function available to other CommonJS modules.

Step 2: Create app.js

const calculateFee = require('./fee');

const totalFee = calculateFee(10000, 2000);

console.log('Total Fee:', totalFee);

Output:

Total Fee: 12000

The expression require('./fee') loads your local module. The ./ indicates that the module is located relative to the current file.

This approach is useful when developing student management systems, billing software, e-commerce websites, and other backend applications.

❖ 3. Third-Party Modules

Third-party modules are packages developed by other developers or organizations. You can install them using npm, the Node.js package manager.

Popular examples include:

  • Express: Build web applications and APIs.

  • Mongoose: Work with MongoDB.

  • mysql2: Connect Node.js applications to MySQL.

  • Nodemailer: Send emails.

  • Multer: Handle file uploads.

  • dotenv: Load configuration values from .env files.

These packages help developers implement common features without building everything from scratch.

Example: Installing and Using Express

First, create a project folder and open its terminal.

mkdir node-modules-demo
cd node-modules-demo
npm init -y
npm install express

Now create app.js:

const express = require('express');

const app = express();
const PORT = 3000;

app.get('/', (req, res) => {
    res.send('Welcome to my Node.js application!');
});

app.listen(PORT, () => {
    console.log(`Server running at http://localhost:${PORT}`);
});

Run the application:

node app.js

Open http://localhost:3000 in your browser. You should see:

Welcome to my Node.js application!

This example demonstrates how a third-party package can simplify web server development.

✦ CommonJS Modules: require() and module.exports

CommonJS is a module system supported by Node.js. It commonly uses two keywords:

  • require() imports a module.

  • module.exports exports a value from a module.

Example: Exporting Multiple Functions

Create calculator.js:

function add(a, b) {
    return a + b;
}

function subtract(a, b) {
    return a - b;
}

module.exports = {
    add,
    subtract
};

Create app.js:

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

console.log(calculator.add(10, 5));
console.log(calculator.subtract(10, 5));

Output:

15
5

You can also use destructuring to access individual functions:

const { add, subtract } = require('./calculator');

console.log(add(20, 10));
console.log(subtract(20, 10));

This makes it convenient to reuse specific functions from a module.

✦ ES Modules: import and export

ES Modules, also known as ESM, provide the standard JavaScript module syntax. They use export to make code available and import to use it in another file.

Step 1: Configure the project

In your package.json, add:

{
  "type": "module"
}

If your existing package.json already contains other properties, keep them and add "type": "module" at the top level.

Step 2: Create calculator.js

export function add(a, b) {
    return a + b;
}

export function multiply(a, b) {
    return a * b;
}

Step 3: Create app.js

import { add, multiply } from './calculator.js';

console.log(add(10, 5));
console.log(multiply(10, 5));

Output:

15
50

Notice that the local file import includes the .js extension. This is the usual approach for relative imports in Node.js ES Modules.

CommonJS and ES Modules are both useful. The right choice depends on your project, its dependencies, and the module system already being used.

✦ How to Choose the Right Module

Use the following simple guide when working on a Node.js project.

Requirement Recommended module type
Read or write files Built-in fs
Handle file paths Built-in path
Reuse your own functions Local module
Build a REST API Third-party Express package
Connect to MySQL Third-party mysql2 package
Work with MongoDB Third-party Mongoose package

Important: Install third-party packages only when your project needs them. Review package documentation, maintenance status, and security considerations before adding dependencies.

✦ Best Practices for Using Node.js Modules

Follow these practices to keep your project clean and manageable.

  1. Use meaningful file names: Names such as studentService.js and feeCalculator.js make the purpose clear.

  2. Keep modules focused: A module should have a clear responsibility instead of containing unrelated logic.

  3. Avoid duplicate code: Move repeated logic into reusable functions or modules.

  4. Protect sensitive configuration: Do not hardcode database passwords, API keys, or other secrets in source code.

  5. Understand your module system: Do not mix CommonJS and ES Module syntax without understanding the compatibility requirements.

  6. Manage dependencies carefully: Use package.json and the lockfile to track project packages.

  7. Test important functions: Verify that modules return correct results for normal and unusual inputs.

✦ Frequently Asked Questions (FAQs)

❖ 1. What is a module in Node.js?

A module is a reusable unit of code that can contain functions, variables, classes, or objects. It helps organize a Node.js application into manageable files.

❖ 2. What are the three common types of Node.js modules?

The three common categories are built-in modules, local modules, and third-party modules.

❖ 3. Do built-in Node.js modules require installation?

No. Built-in modules such as fs, path, and http are provided by Node.js and do not need a separate npm installation.

❖ 4. What is the difference between require() and import?

require() is commonly associated with CommonJS, while import is used by ES Modules. Your project's configuration and file extensions determine which syntax applies.

❖ 5. How do I install a third-party module?

Run npm install package-name in your project directory. For example, npm install express installs Express.

❖ 6. Why should developers use local modules?

Local modules help separate application logic, reduce repeated code, and make projects easier to maintain and test.

✦ Conclusion

Node.js modules are essential for building organized, reusable, and maintainable backend applications. Built-in modules provide core functionality, local modules help structure your own code, and third-party modules offer ready-made tools for common development tasks.

By learning require(), module.exports, import, and export, you can structure your applications more effectively and prepare for advanced topics such as Express.js, REST APIs, database integration, and authentication.

At Param Classes, learners can build their Node.js knowledge through practical programming examples and step-by-step development concepts.

Explore more learning resources at Param Classes and discover website development and digital solutions at ParamWebInfo.

←
Post 5 of 40
→