4) Module System
Node Module
The module system in Node.js is how you organize code into reusable, maintainable pieces. Instead of writing everything in one file, you split functionality into modules and connect them.
There are two module systems in Node.js
i) CommonJS (CJS) → older, default in Node.js
ii) ES Modules (ESM) → modern JavaScript standard
A module is simply a file containing code (functions, variables, objects) that you can reuse in other files.// math.js const add = (a, b) => { return a + b; } module.exports = add;CommonJS (CJS)
This is the traditional Node.js module system.
i) module.exports
Used to export data/functions from a file// math.js const add = (a, b) => a + b; const sub = (a, b) => a - b; module.exports = { add, sub };You can export: Functions, Objects, Variables, Classes.
ii) require()
Used to import modules// app.js const math = require('./math'); console.log(math.add(2, 3)); // 5Key Characteristics of CommonJS
i) Synchronous loading
ii) Used by default in Node.js
iii) Works well on the server
iv) Uses require() and module.exportsES Modules (ESM)
This is the modern JavaScript module system.
To use it in Node.js: Add "type": "module" in package.json OR Use .mjs extension.
i) Export
Used to export values// Named export // math.js export const add = (a, b) => a + b; export const sub = (a, b) => a - b;// Default export // math.js const add = (a, b) => a + b; export default add;ii) Import
Used to import values// Named import import { add, sub } from './math.js';// Default import import add from './math.js';Key Differences
i) Import Timing
require() → runtime (dynamic)
import → compile time (static)
ii) Conditional Importsif (true) { const module = require('./math'); // ✅ allowed } if (true) { import('./math.js'); // ❌ static import not allowed like this }iii) Default vs Named Exports
// ES Modules export default function() {} export const x = 10;// CommonJS module.exports = function() {};When to Use What?
Use CommonJS
i) Legacy Node.js projects
ii) Quick scripts
Use ES Modules
i) Modern applications
ii) Frontend + backend consistency
iii) Better tooling & tree-shakingNode.js has two module systems: CommonJS and ES Modules
require() → imports modules (CJS)
module.exports → exports modules (CJS)
import → imports modules (ESM)
export → exports modules (ESM)
ES Modules are modern, static, and preferred today