Node.js Modules
A module is a JavaScript file whose variables stay private unless you explicitly export them. Splitting a program into modules keeps each file small and lets you reuse code. Node supports two module systems:
| CommonJS (CJS) | ES modules (ESM) | |
|---|---|---|
| Import | const x = require("./x") |
import x from "./x.js" |
| Export | module.exports = ... / exports.name = ... |
export / export default |
| Loading | synchronous, at the line where require runs |
resolved before the code runs |
| File extension | .cjs, or .js by default |
.mjs, or .js with "type": "module" |
Top-level await |
no | yes |
__dirname |
yes | use import.meta.dirname |
ES modules are the JavaScript standard and the recommended choice for new code. CommonJS is still everywhere in existing packages, so you need to read both.
CommonJS: require and module.exports
Imagine two files:
// math.cjs
function add(a, b) { return a + b; }
const PI = 3.14159;
module.exports = { add, PI };// app.cjs
const { add, PI } = require("./math.cjs");
console.log(add(2, 3), PI);This playground creates math.cjs on disk and then requires it, so you can see the whole flow in one run:
const fs = require("node:fs");
fs.writeFileSync("math.cjs", `
function add(a, b) { return a + b; }
const PI = 3.14159;
let calls = 0;
function counted() { return ++calls; }
module.exports = { add, PI, counted };
`);
const { add, PI, counted } = require("./math.cjs");
console.log(add(2, 3), PI);
// Modules are cached: requiring again returns the same object.
const again = require("./math.cjs");
counted();
console.log("calls after two counted():", again.counted());
console.log("same object:", again === require("./math.cjs"));
fs.unlinkSync("math.cjs");5 3.14159
calls after two counted(): 2
same object: true
A module's code runs only once, the first time it is required. Later require calls return the cached module.exports object.
ES modules: import and export
// shapes.mjs
export const unit = "cm";
export function area(w, h) { return w * h; }
export default function describe(w, h) {
return `${w}x${h} ${unit}`;
}// app.mjs
import describe, { area, unit } from "./shapes.mjs";ESM needs the full file name including the extension in relative imports. Here is a runnable version that writes the module first and loads it with a dynamic import():
import { writeFile, rm } from "node:fs/promises";
await writeFile("shapes.mjs", `
export const unit = "cm";
export function area(w, h) { return w * h; }
export default function describe(w, h) { return w + "x" + h + " " + unit; }
`);
const shapes = await import("./shapes.mjs");
console.log(shapes.default(3, 4));
console.log("area:", shapes.area(3, 4), shapes.unit);
console.log("export names:", Object.keys(shapes));
await rm("shapes.mjs");3x4 cm
area: 12 cm
export names: [ 'area', 'default', 'unit' ]
import() returns a promise for the module namespace object; the default export appears under the key default. Static import statements at the top of a file are more common — dynamic import() is for loading modules conditionally or on demand.
Choosing the module system for .js files
Node decides how to treat a .js file from the nearest package.json:
{
"name": "my-app",
"type": "module"
}"type" field |
.js means |
Force the other with |
|---|---|---|
missing or "commonjs" |
CommonJS | .mjs |
"module" |
ES module | .cjs |
Tip: Since Node 22.12, CommonJS code can
require()a synchronous ES module, and ES modules can alwaysimporta CommonJS module. Mixing is much less painful than it used to be.
File paths inside a module
Both systems can tell you where the current file lives — handy for reading files next to your code:
import path from "node:path";
console.log(typeof import.meta.dirname);
console.log(path.basename(import.meta.filename));
console.log(import.meta.url.startsWith("file://"));string
main.mjs
true
In CommonJS the equivalents are the variables __dirname and __filename.
Test yourself
In CommonJS, how do you make a function greet available to other files?
export greetmodule.exports = { greet }public greetrequire.export(greet)
With "type": "module" in package.json, how is a .cjs file treated?
- As an ES module
- As CommonJS
- As JSON
- It is an error
What happens when you require the same module twice?
- Its code runs twice
- The cached exports object is returned
- Node throws an error
- A copy of the exports is made