What is a module in Node.js?
1. What a module is
In Node.js, every file is a separate module.
When you create a file math.js, Node.js automatically wraps it in an internal function:
(function (exports, require, module, __filename, __dirname) {
// your code
});Thanks to this:
- every file has its own scope (no global variables);
- you can export just what's needed;
- you can import code from other modules.
2. Types of modules in Node.js
| Type | Examples | Description |
|---|---|---|
| Built-in (core modules) | fs, path, os, http, events, crypto | Shipped with Node.js |
| User-defined (user modules) | ./math.js, ./config.js | Your own files and utilities |
| Third-party | express, mongoose, chalk | Installed via npm |
3. CommonJS modules (the default)
math.js
const PI = 3.14;
function add(a, b) {
return a + b;
}
module.exports = { PI, add };app.js
const math = require('./math');
console.log(math.add(2, 3)); // 5
console.log(math.PI); // 3.14Here:
module.exports→ the objectrequire()returns;require()→ the function that imports a module.
4. ES Modules (the modern standard)
If package.json has "type": "module", you can use ES6 syntax:
math.js
export const PI = 3.14;
export function add(a, b) {
return a + b;
}app.js
import { add, PI } from './math.js';
console.log(add(2, 3)); // 5
console.log(PI); // 3.14Supported natively since Node.js v13+, but it requires "type": "module" or the .mjs extension.
5. How Node.js loads a module
When you call require('./math'), Node.js goes through 5 steps:
- Path resolution
Figures out where the file is (
.js,.json,.node). - Caching If the module is already loaded, it's returned from the cache.
- Loading Node.js reads the file's content from disk.
- Wrapping The module's code is wrapped in an internal function.
- Execution
Node.js runs the code and returns
module.exports.
6. An example of the internal wrapper
Under the hood, Node.js does roughly this:
(function (exports, require, module, __filename, __dirname) {
const PI = 3.14;
module.exports = { PI };
});Thanks to this:
- the module is isolated;
- you get access to paths (
__dirname,__filename); - code can be exported via
module.exports.
7. Node.js's built-in (core) modules
| Module | Purpose |
|---|---|
fs | Filesystem access |
path | Working with paths |
os | OS information |
http, https | Servers and requests |
events | Working with events |
crypto | Encryption |
url | URL parsing |
util | Debugging utilities |
Example:
const os = require('os');
console.log(os.platform()); // 'win32' or 'linux'8. Third-party modules (npm)
Installed via npm:
npm install chalkUsage:
import chalk from 'chalk';
console.log(chalk.green('Success!'));They live in the node_modules folder
and are listed in package.json.
9. Module caching
Node.js loads a module once, then reads it from cache afterward:
require('./math');
require('./math'); // the second call doesn't re-read the fileThis speeds things up, but if a module needs re-initializing, the cache can be cleared:
delete require.cache[require.resolve('./math')];10. Path and scope
A module can be:
- local (
./math.js); - global (a built-in like
fs); - installed via npm (
express).
Node.js looks for them in this order:
- Built-in (
fs,path); - Local (
./or../); - In
node_modules(walking up from the current folder).
11. An example project layout
project/
├── package.json
├── app.js
├── config/
│ └── db.js
├── utils/
│ └── logger.js
└── routes/
└── userRoutes.jsIn app.js:
const db = require('./config/db');
const logger = require('./utils/logger');
const routes = require('./routes/userRoutes');Every file is a module. Every module exports its own functions and doesn't interfere with the rest.
12. Quick summary
| Point | CommonJS | ES Modules |
|---|---|---|
| Import | require() | import |
| Export | module.exports | export |
| Support | By default | Via "type": "module" or .mjs |
| Loading | Synchronous | Asynchronous |
| Tree-shaking | No | Yes |
| Use case | Older and server projects | Modern modules and frontend |
In one sentence
A module in Node.js is an independent file of code (JS, JSON, or a native binary) that exports specific data or functions and can be imported into other files via
require()orimport.
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.