Node.js: Code Outside the Browser / Working with Modules

CommonJS

๐Ÿ”„ 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.exports

  • Import 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.

  • .js is the default file extension; no package.json config required.