CommonJS vs ES Modules (Node.js)
Node.js supports two module systems: CommonJS (require/module.exports), its original synchronous system, and ES Modules (import/export), the modern JavaScript standard. They differ in syntax, loading, and a few behaviors.
Node.js
CommonJS (CJS) is Node's legacy default: require() loads modules synchronously and returns module.exports. It is dynamic — you can require() conditionally inside a function — and gives you __dirname and __filename for free. Most older packages and tutorials use it.
ES Modules (ESM) use import/export, are statically analyzed (which enables tree-shaking and better tooling), support top-level await, and provide live bindings. Node treats a file as ESM via the .mjs extension or "type": "module" in package.json.
They interoperate but with edges: ESM can import CommonJS packages, but a CommonJS file cannot require() an ESM file (it must use dynamic import()). For new projects pick one consistently; ESM is the forward-looking choice, while CJS remains common in existing codebases and many npm packages.
Syntax
require(...) // CommonJS import ... // ESMExamples
JavaScript
// CommonJS
const fs = require("fs");
module.exports = { go };
// ES Module
import fs from "node:fs";
export function go() {}