Modules are isolated code blocks that encapsulate internal variables, functions, and classes while exposing explicit interfaces to other parts of your Node.js application. Node.js supports two module systems: legacy CommonJS (CJS) and modern ECMAScript Modules (ESM).
flowchart TD
subgraph CommonJS ["CommonJS (Synchronous)"]
C1["require() invocation"] --> C2["Load & Evaluate File Synchronously"]
C2 --> C3["Export module.exports object"]
end
subgraph ESM ["ES Modules (Asynchronous / Static)"]
E1["Static import declaration"] --> E2["Parse Module Graph & Imports"]
E2 --> E3["Instantiate & Link Bindings"]
E3 --> E4["Evaluate Module Top-Level Code"]
end
.mjs or "type": "module")// mathUtils.js - Named exports & default export
export const add = (a, b) => a + b;
export const multiply = (a, b) => a * b;
export default class Calculator {
subtract(a, b) {
return a - b;
}
}
// app.js - Importing ES Modules
import Calculator, { add, multiply } from './mathUtils.js';
const calc = new Calculator();
console.log(`Sum: ${add(10, 5)}`); // 15
console.log(`Product: ${multiply(4, 3)}`); // 12
console.log(`Diff: ${calc.subtract(20, 8)}`);// 12
node:)Always use the explicit node: prefix when importing core modules:
import fs from 'node:fs/promises';
import path from 'node:path';
import http from 'node:http';
node: Protocol Prefix: Always import core built-in modules using node:fs or node:path to prevent ambiguity with third-party npm packages.require() cannot synchronously import ESM files; convert project bases cleanly to ESM../utils.js, not ./utils).Create a module logger.js that exports a default Logger class and a named helper function formatTimestamp(), then import both into index.js.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With