Node.js Modules
Learn how Node.js organizes code into reusable modules using CommonJS require/module.exports and modern ES module import/export syntax.
Why Modules?
As a Node.js application grows, keeping everything in one file becomes unmanageable. Modules let you split code into focused files, each responsible for one thing, and then combine them by explicitly importing what you need. Node.js supports two module systems: the original CommonJS format and modern ECMAScript (ES) modules.
CommonJS: require and module.exports
CommonJS is Node's original module system. Every file is treated as its own module with a private scope; nothing is exposed to other files unless you attach it to module.exports. Other files pull it in with require().
CommonJS Modules
// math-utils.js
function add(a, b) {
return a + b;
}
function multiply(a, b) {
return a * b;
}
module.exports = { add, multiply };
// app.js
const { add, multiply } = require("./math-utils");
console.log(add(2, 3)); // 5
console.log(multiply(4, 5)); // 20ES Modules: import and export
Node.js also supports the same import/export syntax used in modern browsers. To enable it, set "type": "module" in package.json, or use the .mjs file extension. ES modules are statically analyzed, support named and default exports, and are the standard going forward.
ES Modules
// math-utils.mjs
export function add(a, b) {
return a + b;
}
export default function square(n) {
return n * n;
}
// app.mjs
import square, { add } from "./math-utils.mjs";
console.log(add(2, 3)); // 5
console.log(square(6)); // 36- require() is synchronous and can be called conditionally anywhere in a file.
- import is static — it's hoisted and must appear at the top level, not inside an if block.
- CommonJS exports a single module.exports object; ES modules can have many named exports plus one default export.
- Node.js can run both systems in the same project, but a single file must pick one.
Combining Built-in and Local Modules
// server-info.js (CommonJS)
const os = require("os"); // built-in module
const { add } = require("./math-utils"); // local module
console.log("Host platform:", os.platform());
console.log("2 + 2 =", add(2, 2));Exercise: Node.js Modules
How do you import another module in a standard Node.js CommonJS file?