Node.js applications are built on a modular architecture that promotes reusability and maintainability. The module system is a foundational feature in Node.js that allows you to encapsulate code into manageable units.
In this guide, we’ll cover everything you need to know about the Node.js module system—from the core concept to writing your own modules, importing external packages, and understanding how CommonJS works under the hood.
Table of Contents
- What Are Modules in Node.js?
- Why Use Modules?
- Types of Modules in Node.js
- Core Modules
- Local/User-defined Modules
- Third-Party Modules (npm)
- The
require()
Function in Node.js - Exporting from a Module
module.exports
exports
- Pitfalls to Avoid
- Loading Order & Module Caching
- Built-in Modules: Examples and Use Cases
- Installing and Using External Modules
- ES Modules in Node.js (ESM vs CommonJS)
- Conclusion
1. What Are Modules in Node.js?
A module is simply a JavaScript file that contains reusable code. In Node.js, every file is treated as a separate module, allowing developers to encapsulate functionality and expose only the parts that need to be used elsewhere.
2. Why Use Modules?
Using modules provides several benefits:
- Code organization: Break your application into logical units.
- Reusability: Functions can be used across multiple files or projects.
- Maintainability: Changes in one module don’t directly affect others.
- Namespace isolation: Variables and functions inside a module won’t interfere with global scope.
3. Types of Modules in Node.js
Core Modules
These are built-in modules that come with Node.js. No installation required.
Examples:
fs
– File systemhttp
– HTTP utilitiespath
– File path utilitiesos
– Operating system details
Usage:
const fs = require('fs');
const data = fs.readFileSync('example.txt', 'utf8');
console.log(data);
Local/User-defined Modules
These are your custom modules.
math.js:
function add(a, b) {
return a + b;
}
module.exports = { add };
app.js:
const math = require('./math');
console.log(math.add(2, 3)); // 5
Third-Party Modules (npm)
Modules published by the community. You install them using npm
.
npm install express
const express = require('express');
const app = express();
4. The require()
Function in Node.js
The require()
function is used to load modules. It can import:
- Core modules (e.g.,
require('fs')
) - Local files (e.g.,
require('./myFile')
) - Node modules from
node_modules
(e.g.,require('express')
)
Behind the scenes, require()
:
- Resolves the file path
- Wraps the file in a function
- Executes the file
- Caches the result
5. Exporting from a Module
You can export any variable, function, or class using:
Using module.exports
// calculator.js
function subtract(a, b) {
return a - b;
}
module.exports = subtract;
// app.js
const subtract = require('./calculator');
console.log(subtract(10, 4)); // 6
Using exports
// user.js
exports.getUser = () => ({ id: 1, name: 'Alice' });
Pitfalls with exports
The following does not work:
exports = {
getUser: () => { return { name: 'John' }; }
};
Because exports
is just a reference to module.exports
. Reassigning it breaks the link.
6. Loading Order & Module Caching
Node.js caches modules after the first time they are loaded. Requiring the same module again will return the cached version.
This boosts performance, but if you want a fresh copy of a module (not common), you’ll need to manually clear the cache.
delete require.cache[require.resolve('./module.js')];
7. Built-in Modules: Examples and Use Cases
Here are a few built-in modules you’ll use frequently:
path
: Handling and transforming file paths
const path = require('path');
console.log(path.join(__dirname, 'file.txt'));
os
: Operating system information
const os = require('os');
console.log(os.platform(), os.freemem());
events
: Working with custom events
const EventEmitter = require('events');
const emitter = new EventEmitter();
emitter.on('greet', () => console.log('Hello!'));
emitter.emit('greet');
8. Installing and Using External Modules
Install modules using npm:
npm install moment
const moment = require('moment');
console.log(moment().format('YYYY-MM-DD'));
To remove:
npm uninstall moment
To install as a dev dependency:
npm install --save-dev jest
9. ES Modules in Node.js (ESM vs CommonJS)
Node.js traditionally uses CommonJS (require/module.exports
), but ES Modules (import/export
) are now supported natively.
To use ES Modules:
- Use
.mjs
extension or set"type": "module"
inpackage.json
// utils.mjs
export function sum(a, b) {
return a + b;
}
// main.mjs
import { sum } from './utils.mjs';
console.log(sum(4, 5));
You can’t mix require()
and import
in the same file unless using dynamic import()
.
10. Conclusion
The Node.js module system is one of the platform’s core strengths. It encourages modular design and makes code easier to manage, reuse, and test. Whether you’re working with built-in modules, custom logic, or npm packages, understanding how modules work is essential for writing scalable Node.js applications.