Modules & npm
Two module systems, one ecosystem
Section titled “Two module systems, one ecosystem”Node.js ships with two module systems. CommonJS (CJS) is the original system and uses require() to load modules synchronously. ECMAScript Modules (ESM) is the modern standard, shared with browsers, and uses import / export statements.
Both systems are fully supported in current Node.js versions. Which one a file uses depends on the file extension and the "type" field in the nearest package.json.
CJS vs ESM at a glance
Section titled “CJS vs ESM at a glance”| CommonJS | ESM | |
|---|---|---|
| Syntax | require() / module.exports | import / export |
| File extension | .js (default) or .cjs | .mjs, or .js when "type": "module" |
"type" in package.json | "commonjs" (or absent) | "module" |
| Loading | Synchronous | Asynchronous (static analysis) |
Top-level await | Not supported | Supported |
What this module covers
Section titled “What this module covers”| Lesson | Topic |
|---|---|
| Overview (this page) | CJS vs ESM comparison and module system basics |
| package.json Deep Dive | Key fields, semver ranges, and npm init |
| Module Resolution | How Node finds files, the exports map, and bare specifiers |
| Managing Dependencies | Installing, updating, and auditing packages with npm |
| Publishing Packages | Preparing and publishing a package to the npm registry |
ESM in action
Section titled “ESM in action”The snippet below uses ESM import to load the built-in path module and print the platform path separator — the character Node uses between directory components (/ on Unix, \ on Windows):
Needs the Node.js runtime — open in StackBlitz to run.