๐ CommonJS (CJS)
CommonJS is the module system Node.js has used from the start, to split code into files and reuse it.
Export with
module.exportsImport with
require()Loads modules synchronously
๐ Features
One file = one module
Private scope by default
Built into Node.js โ no setup needed
Modules are cached after the first load, so requiring the same file twice doesn't re-run it
๐งช Sample Code
math.js
function add(a, b) {
return a + b;
}
module.exports = add;app.js
const add = require('./math');
console.log(add(2, 3)); // 5๐ When to Use CommonJS
โก Quick backend scripts โ faster to set up, simpler syntax
๐๏ธ Legacy Node.js projects that already use
require()throughout
๐ก Good to Know
Requiring a module dynamically (conditionally, inside an
if) works fine in CJS โ that's harder in ES Modules..jsis the default file extension; nopackage.jsonconfig required.