As a project grows, putting everything in one file becomes unmanageable. Modules let you split code into separate files and share only what you choose.
Node.js has two module systems:
- ES Modules (
import/export): the official JavaScript standard, the same syntax React uses. This is what you should learn first and use in new code. - CommonJS (
require/module.exports): Node.js's older system. You'll still meet it in many existing projects and npm packages, including the DevTinder project in Season 2.
The chapter is split into tabs, so you can read one system at a time without mixing them up. Start with ES Modules. Open CommonJS when you need to read older code, and Compare & mix when you want to see both side by side.
In this chapter you'll learn
- what a module is and why every file has its own private scope
- ES Modules: named and default exports,
import * as, folders, JSON, live bindings, top-levelawait, dynamicimport(),import.meta - why imports that work in React fail in Node.js
- CommonJS:
module.exports,require, and theexportstrap - how Node.js decides which system a file uses, and how the two work together
Before you start: read Chapter 03: Let's Write the code. Runnable examples: Code/esm/ (ES Modules) and Code/ (CommonJS).
What is a module?
A module is simply a JavaScript file that can share code with other files.
Imagine each file is a room with a closed door. Variables and functions inside the room are private. If you want other rooms to use something, you pass it through the door on purpose. In ES Modules that door is the export keyword; in CommonJS it's module.exports.
Why bother? Because files then can't accidentally overwrite each other's variables. (In browsers, separate <script> tags do share variables, which causes exactly that problem.)
ES Modules: import and export
ES Modules were added to JavaScript in 2015 (ES6). Browsers support them, React and every modern framework use them, and Node.js supports them fully.
A runnable version of this tab's examples is in Code/esm/ (run node app.js inside it).
Your first module
// sum.js
const secret = "nobody outside this file can see me";
export function calculateSum(a, b) {
return a + b;
}// sum.js
const secret = "nobody outside this file can see me";
export function calculateSum(a, b) {
return a + b;
}// app.js
import { calculateSum } from "./sum.js";
console.log(calculateSum(10, 20)); // 30
console.log(secret); // ReferenceError: secret is not defined// app.js
import { calculateSum } from "./sum.js";
console.log(calculateSum(10, 20)); // 30
console.log(secret); // ReferenceError: secret is not definedexportputscalculateSumthrough the "door".secrethas noexport, so it stays private.import { calculateSum } from "./sum.js"brings it intoapp.js. Note the./(a file next to this one) and the.jsextension: Node.js needs both.
Turning ES Modules on
Add one line to your project's package.json, and every .js file in the project becomes an ES Module:
{
"name": "my-app",
"type": "module"
}{
"name": "my-app",
"type": "module"
}You can also run npm pkg set type=module to add it. Alternatively, name a single file .mjs (for example app.mjs), and it is always an ES Module. React projects made with Vite already have "type": "module".
Without "type": "module", import in a .js file is an error on older Node.js versions, and a slow guess with a MODULE_TYPELESS_PACKAGE_JSON warning on newer ones. Always set it.
Named exports: share many things
A file can have many named exports. Put export in front of each declaration:
// calculate/sum.js
export function calculateSum(a, b) {
return a + b;
}
export const PI = 3.14159;// calculate/sum.js
export function calculateSum(a, b) {
return a + b;
}
export const PI = 3.14159;Or declare things normally and export a list at the bottom. Many teams prefer this, because you see the file's whole public "door" in one place:
// calculate/sum.js
function calculateSum(a, b) {
return a + b;
}
const PI = 3.14159;
export { calculateSum, PI };// calculate/sum.js
function calculateSum(a, b) {
return a + b;
}
const PI = 3.14159;
export { calculateSum, PI };Import named exports with curly braces, using the exact names:
// app.js
import { calculateSum, PI } from "./calculate/sum.js";
console.log(calculateSum(2, 3)); // 5
console.log(PI); // 3.14159// app.js
import { calculateSum, PI } from "./calculate/sum.js";
console.log(calculateSum(2, 3)); // 5
console.log(PI); // 3.14159Need a different name, for example because two modules both export add? Rename with as, on either side:
import { calculateSum as add } from "./calculate/sum.js"; // rename while importing
export { calculateSum as sum }; // rename while exportingimport { calculateSum as add } from "./calculate/sum.js"; // rename while importing
export { calculateSum as sum }; // rename while exportingimport { calculateSum } from ... looks like object destructuring, but it isn't. You can't write defaults ({ a = 1 }) or nested patterns there, and export { a, b } is not an object: export { a: b } is a syntax error. They're a special list of names.
Default export: the main thing of a file
A file can have at most one default export. It's imported without braces, under any name you like:
// logger.js
export default function log(message) {
console.log(`[LOG] ${message}`);
}// logger.js
export default function log(message) {
console.log(`[LOG] ${message}`);
}// app.js
import log from "./logger.js"; // any name works...
import writeLog from "./logger.js"; // ...this is the same function
log("server started"); // [LOG] server started// app.js
import log from "./logger.js"; // any name works...
import writeLog from "./logger.js"; // ...this is the same function
log("server started"); // [LOG] server startedA file can have a default and named exports. Import both in one line, default first:
// counter.js
export let count = 0;
export function increment() { count++; }
export default function describe() { return `count is ${count}`; }// counter.js
export let count = 0;
export function increment() { count++; }
export default function describe() { return `count is ${count}`; }import describe, { count, increment } from "./counter.js";import describe, { count, increment } from "./counter.js";That's exactly the React pattern: export default function App() {} for the component, and import React, { useState } from "react".
Many teams prefer named exports for most code: the name is fixed, so search, refactoring and editor auto-imports all work, and a typo is an error instead of a silently wrong name. Use a default export when a file really has one main thing (a React component, an Express app).
Import everything: import * as
import * as name collects all named exports into one read-only object:
import * as math from "./calculate/sum.js";
console.log(math.calculateSum(2, 3)); // 5
console.log(math.PI); // 3.14159import * as math from "./calculate/sum.js";
console.log(math.calculateSum(2, 3)); // 5
console.log(math.PI); // 3.14159Just run a file: import "./file.js"
Sometimes you only want a file to run (to load settings, register something), and you don't need anything from it:
import "./setup.js"; // runs setup.js once, imports nothingimport "./setup.js"; // runs setup.js once, imports nothingBuilt-in modules and packages
Node's built-in (core) modules and packages from node_modules are imported by name, without ./:
import fs from "node:fs"; // the whole built-in module
import { readFile } from "node:fs/promises"; // or only what you need
import path from "node:path";
import express from "express"; // a package installed with npmimport fs from "node:fs"; // the whole built-in module
import { readFile } from "node:fs/promises"; // or only what you need
import path from "node:path";
import express from "express"; // a package installed with npmThe node: prefix makes it obvious that you mean a built-in module. Prefer it.
| You write | Node.js looks for |
|---|---|
"./sum.js", "../utils/sum.js" | a file, relative to the current file |
"node:fs" | a built-in module |
"express" | a package in node_modules |
Coming from React? Write the full path
In a React app, import Button from "./Button", import { api } from "./services" and import "./App.css" all work. That's not ES Modules doing it: the bundler (Vite, webpack, Next.js) fills in the extension, finds the folder's index.js and turns CSS and images into modules. Node.js follows the ES Modules standard exactly, like a browser does:
| In a React project | In Node.js | Error you'll see in Node |
|---|---|---|
import x from "./utils" | import x from "./utils.js" | ERR_MODULE_NOT_FOUND |
import x from "./components" | import x from "./components/index.js" | ERR_UNSUPPORTED_DIR_IMPORT |
import data from "./data.json" | ... with { type: "json" } (below) | ERR_IMPORT_ATTRIBUTE_MISSING |
import "./App.css" | not possible | ERR_UNKNOWN_FILE_EXTENSION |
Folders: an index.js barrel file
You can group a folder's modules behind one door with an index.js that re-exports them: it exports things from other files without using them itself. This is called a barrel file.
// calculate/index.js
export { calculateSum } from "./sum.js";
export { calculateMultiply } from "./multiply.js";
// export * from "./sum.js"; // or: re-export ALL named exports of sum.js
// export { default as log } from "./logger.js"; // turn another file's default into a named export// calculate/index.js
export { calculateSum } from "./sum.js";
export { calculateMultiply } from "./multiply.js";
// export * from "./sum.js"; // or: re-export ALL named exports of sum.js
// export { default as log } from "./logger.js"; // turn another file's default into a named export// app.js
import { calculateSum, calculateMultiply } from "./calculate/index.js"; // write index.js yourself// app.js
import { calculateSum, calculateMultiply } from "./calculate/index.js"; // write index.js yourselfJSON files
JSON needs an import attribute that says "this is JSON":
// data.json → { "name": "Akshad Jaiswal", "city": "Pune" }
import data from "./data.json" with { type: "json" };
console.log(data.city); // "Pune"// data.json → { "name": "Akshad Jaiswal", "city": "Pune" }
import data from "./data.json" with { type: "json" };
console.log(data.city); // "Pune"The whole JSON object is the default export, so import { city } from "./data.json" doesn't work.
A module runs only once
// sum.js
console.log("sum.js is running");
export const s = 1;// sum.js
console.log("sum.js is running");
export const s = 1;// app.js
import "./sum.js";
import "./sum.js";
import { s } from "./sum.js";// app.js
import "./sum.js";
import "./sum.js";
import { s } from "./sum.js";Output:
sum.js is runningsum.js is runningJust once. Node.js runs each module the first time it's needed and then remembers (caches) it. Every file that imports it gets the same module. That's why it's safe to import the same module from many files, and why things like a database connection set up at the top of a module happen only once.
Imports are loaded before your code runs
import lines are not run one by one like normal code. Before running a single line of a file, Node.js reads all its imports, loads those modules (and their imports), connects the names, and only then runs the code. So imports behave as if they were at the very top (they're hoisted):
// app.js
console.log("first line of app");
import "./sum.js"; // written second, but loaded first// app.js
console.log("first line of app");
import "./sum.js"; // written second, but loaded firstOutput:
sum.js is running
first line of appsum.js is running
first line of appBecause of this, an import statement must be at the top level of a file, never inside an if, a function or a loop, and the path must be a plain string, not a variable. This fixed structure lets tools see exactly which exports are used, and remove unused ones from a bundle (tree-shaking). For loading something conditionally, use import() (below).
Live bindings: imports stay up to date
An imported name is a live binding: a read-only view of the exporting module's own variable. When the module changes the variable, every importer sees the new value:
// counter.js
export let count = 0;
export function increment() { count++; }// counter.js
export let count = 0;
export function increment() { count++; }// app.js
import { count, increment } from "./counter.js";
console.log(count); // 0
increment();
console.log(count); // 1 ← sees the change// app.js
import { count, increment } from "./counter.js";
console.log(count); // 0
increment();
console.log(count); // 1 ← sees the changeIt's read-only from the outside: count = 5 in app.js throws TypeError: Assignment to constant variable. Only the module that owns a variable can change it, which keeps data flow predictable. To let others change it, export a function (like increment).
Top-level await
You can use await at the top of a module, outside any async function. Modules that import this one wait until it has finished:
// config.js
import { readFile } from "node:fs/promises";
const text = await readFile(import.meta.dirname + "/config.json", "utf-8");
export const config = JSON.parse(text);// config.js
import { readFile } from "node:fs/promises";
const text = await readFile(import.meta.dirname + "/config.json", "utf-8");
export const config = JSON.parse(text);Dynamic import(): load on demand
When you need to load something conditionally or later, use the function form import(). It can go anywhere, accepts a computed path, and returns a Promise for the module:
if (process.env.NODE_ENV === "development") {
const { default: morgan } = await import("morgan"); // the default export is under .default
app.use(morgan("dev"));
}if (process.env.NODE_ENV === "development") {
const { default: morgan } = await import("morgan"); // the default export is under .default
app.use(morgan("dev"));
}It's the same mechanism behind React.lazy(() => import("./Page")).
import.meta: where am I?
import.meta holds information about the current module, most usefully its location on disk:
import path from "node:path";
console.log(import.meta.filename); // /home/you/app/server.js (Node 20.11+)
console.log(import.meta.dirname); // /home/you/app (Node 20.11+)
console.log(import.meta.url); // file:///home/you/app/server.js
// Build paths relative to this file, no matter which folder you run node from
const dataPath = path.join(import.meta.dirname, "data.json");import path from "node:path";
console.log(import.meta.filename); // /home/you/app/server.js (Node 20.11+)
console.log(import.meta.dirname); // /home/you/app (Node 20.11+)
console.log(import.meta.url); // file:///home/you/app/server.js
// Build paths relative to this file, no matter which folder you run node from
const dataPath = path.join(import.meta.dirname, "data.json");Strict mode is always on
Every ES Module runs in strict mode automatically: for example, assigning to an undeclared variable throws an error instead of silently creating a global. And this at the top of a module is undefined.
Circular imports
If a.js imports b.js and b.js imports a.js, Node.js still loads both. But if b.js uses a's export before a.js has run that line, you get ReferenceError: Cannot access 'a' before initialization. Fix it by moving the shared code into a third module.
Common mistakes with ES Modules
- No
"type": "module"inpackage.json(and not a.mjsfile):importfails or triggers a warning. - Leaving out the extension or
index.js:import x from "./sum"andimport x from "./calculate"work in React (thanks to the bundler) but fail in Node.js. Write"./sum.js"and"./calculate/index.js". - Forgetting
./:import ... from "sum.js"looks for a package, not your file. - Default vs named mix-ups:
export default { a, b }exports one object, soimport { a } from "./m.js"fails withdoes not provide an export named 'a'. Useexport { a, b }for named imports. The reverse,import x froma file with no default export, fails withdoes not provide an export named 'default'. - Changing an import: imports are read-only (
TypeError: Assignment to constant variable.). Export a function that changes the value instead. importinside anifor a function: aSyntaxError. Useawait import()there.__dirname: doesn't exist here (ReferenceError: __dirname is not defined in ES module scope). Useimport.meta.dirname.
Key takeaways: ES Modules
- Every file is a module with its own private scope. Share with
export, bring in withimport. - Turn ESM on with
"type": "module"inpackage.json(or use.mjsfiles). - Named exports (many per file, imported with
{ }by exact name, renamed withas); one default export (imported without braces, any name);import * asfor all named exports;export ... fromto re-export. - In Node.js, always write
./, the file extension andindex.js; JSON needswith { type: "json" }. - Imports are hoisted, must be at the top level, and are live, read-only bindings. Each module runs once.
- ES Modules also give you top-level
await, dynamicimport()andimport.meta.dirname.
Interview questions: ES Modules
Q1. What is the difference between a named export and a default export?
A module can have many named exports, imported with braces using their exact names (import { a, b } from './m.js', renamed with as). It can have at most one default export, imported without braces under any name (import anything from './m.js'). A file can have both: import React, { useState } from 'react'. Named exports make refactoring, search and auto-imports easier, so many teams prefer them for everything except a file's single main thing, like a React component.
Q2. What are live bindings? What does this print?
// counter.js
export let count = 0;
export function increment() { count++; }
// app.js
import { count, increment } from "./counter.js";
increment();
console.log(count);// counter.js
export let count = 0;
export function increment() { count++; }
// app.js
import { count, increment } from "./counter.js";
increment();
console.log(count);It prints 1. An imported name is a live binding: a read-only view of the exporting module's own variable, so app.js sees the update. Live bindings are read-only: count = 5 in app.js throws a TypeError.
Q3. Why does import Button from "./Button" work in a React app but fail in Node.js?
Because in React the bundler (Vite, webpack, Next.js) resolves imports, and it adds the missing extension and finds folder index.js files for you. Node.js follows the ES Module standard strictly, like a browser: the path must be complete, ./Button.js (otherwise ERR_MODULE_NOT_FOUND), and folders must name their file, ./components/index.js (otherwise ERR_UNSUPPORTED_DIR_IMPORT). Importing CSS or images is also a bundler feature, not part of ES Modules.
Q4. How do you get the current file's folder in an ES Module?
import.meta.dirname (and import.meta.filename for the file itself), available since Node.js 20.11. On older versions: path.dirname(fileURLToPath(import.meta.url)), with fileURLToPath from node:url. __dirname doesn't exist in ES Modules.
Q5. What is dynamic import(), and when do you use it?
import("module") loads a module at runtime and returns a Promise of the module object (the default export is under .default). Unlike a static import, it can be used anywhere and with a computed path. Use it to load a module conditionally (only in development, only for some users), lazily (faster startup, code-splitting like React.lazy), or when the path is only known at runtime.
Q6. Why must a static import be at the top level, and why does that enable tree-shaking?
Node.js (and bundlers) read all static imports before running any code, to build the full module graph and connect imported names to exported variables. That only works if imports are fixed: top level, plain string paths, no conditions. Because the structure is known without running the code, a bundler can see that an export is never imported anywhere and drop it from the output: tree-shaking.
Q7. What is top-level await?
Using await at the top of a module, outside any async function: const config = await loadConfig();. Modules that import it wait until it finishes before they run. It's handy for loading configuration or connecting to a database during startup. It works because ES Modules are loaded in phases that can be asynchronous (Chapter 05 explains how).
Q8. If a.js does export default { x, y }, why does import { x } from "./a.js" fail?
Because export default { x, y } exports one value, an object, as the default export; it doesn't create named exports x and y. The { } in an import names exports, not object properties, so Node reports does not provide an export named 'x'. Either use export { x, y }, or import the default and destructure it: import a from './a.js'; const { x } = a;.
Q9. If you import the same module in five files, how many times does it run?
Once. Each module is evaluated the first time it's needed, then cached; every importer is connected to the same module instance. So all five files share its state, and top-level code (a log, a database connection) runs a single time.
Q10. What happens with a circular import?
If module A imports B and B imports A, Node.js still loads both, but one of them runs first and can't see the other's exports yet. Using such an import too early throws ReferenceError: Cannot access 'x' before initialization. Fix it by moving the shared code into a third module, or by only using the import inside a function that runs later.
CommonJS: require and module.exports
CommonJS is the module system Node.js used before ES Modules existed. It's still very common: many npm packages, older company codebases and the DevTinder project in Season 2 use it. You don't need it for new code, but you need to be able to read it.
A .js file is CommonJS when the project's package.json has "type": "commonjs" (or, mostly, no "type" at all), or when the file is named .cjs. The runnable examples are in Code/.
Your first CommonJS module
// sum.js
const secret = "nobody outside this file can see me";
function calculateSum(a, b) {
return a + b;
}
module.exports = calculateSum; // only this goes out through the "door"// sum.js
const secret = "nobody outside this file can see me";
function calculateSum(a, b) {
return a + b;
}
module.exports = calculateSum; // only this goes out through the "door"// app.js
const calculateSum = require("./sum"); // bring it into this file
console.log(calculateSum(10, 20)); // 30
console.log(secret); // ReferenceError: secret is not defined// app.js
const calculateSum = require("./sum"); // bring it into this file
console.log(calculateSum(10, 20)); // 30
console.log(secret); // ReferenceError: secret is not definedrequire("./sum")runssum.jsand returns whatever it put inmodule.exports.secretstays private.
How does Node.js keep each file private here? It quietly wraps every CommonJS file inside a function before running it. You'll see that wrapper, and everything require does step by step, in Chapter 05: Diving in to NodeJS github repo.
Exporting more than one thing
Usually a module shares several things. Export an object:
// calculate/sum.js
function calculateSum(a, b) {
return a + b;
}
const PI = 3.14159;
module.exports = { calculateSum, PI };
// same as: module.exports = { calculateSum: calculateSum, PI: PI };// calculate/sum.js
function calculateSum(a, b) {
return a + b;
}
const PI = 3.14159;
module.exports = { calculateSum, PI };
// same as: module.exports = { calculateSum: calculateSum, PI: PI };Import it with destructuring to pick out just what you need:
// app.js
const { calculateSum, PI } = require("./calculate/sum");
console.log(calculateSum(2, 3)); // 5
console.log(PI); // 3.14159// app.js
const { calculateSum, PI } = require("./calculate/sum");
console.log(calculateSum(2, 3)); // 5
console.log(PI); // 3.14159module.exports starts out as an empty object {}, so you can also add properties to it one by one:
module.exports.calculateSum = calculateSum;
module.exports.PI = PI;module.exports.calculateSum = calculateSum;
module.exports.PI = PI;The exports shortcut, and the trap
Node.js also gives every CommonJS file a variable called exports, which points to the same object as module.exports. So this works too:
exports.calculateSum = calculateSum; // ✅ adds a property to the shared objectexports.calculateSum = calculateSum; // ✅ adds a property to the shared objectBut this does not work:
exports = { calculateSum }; // ❌ nothing is exported!exports = { calculateSum }; // ❌ nothing is exported!Why? require always returns module.exports. Writing exports = {...} points the local exports variable at a new object, while module.exports still points at the old, empty one.
To avoid this trap entirely, many teams always write module.exports = { ... } at the bottom of the file. It's clear and it always works.
How require finds files
require("./sum"); // a file next to this one: ./sum.js
require("../utils/sum"); // go up one folder first
require("./calculate"); // a FOLDER: loads ./calculate/index.js
require("./data.json"); // a JSON file: parsed into a JS object
require("node:fs"); // a built-in (core) Node.js module
require("express"); // a package installed in node_modulesrequire("./sum"); // a file next to this one: ./sum.js
require("../utils/sum"); // go up one folder first
require("./calculate"); // a FOLDER: loads ./calculate/index.js
require("./data.json"); // a JSON file: parsed into a JS object
require("node:fs"); // a built-in (core) Node.js module
require("express"); // a package installed in node_modules- Paths starting with
./,../or/are files on disk. You can leave out.js. - A bare name (
"express") is a core module or a package fromnode_modules. - If you
requirea folder, Node.js loads itsindex.js:
// calculate/index.js
const { calculateSum } = require("./sum");
const { calculateMultiply } = require("./multiply");
module.exports = { calculateSum, calculateMultiply };// calculate/index.js
const { calculateSum } = require("./sum");
const { calculateMultiply } = require("./multiply");
module.exports = { calculateSum, calculateMultiply };// app.js
const { calculateSum, calculateMultiply } = require("./calculate");// app.js
const { calculateSum, calculateMultiply } = require("./calculate");- A JSON file is read and parsed for you:
// data.json → { "name": "Akshad Jaiswal", "city": "Pune" }
const data = require("./data.json");
console.log(data.city); // "Pune"// data.json → { "name": "Akshad Jaiswal", "city": "Pune" }
const data = require("./data.json");
console.log(data.city); // "Pune"A CommonJS module runs only once
// sum.js
console.log("sum.js is running");
module.exports = (a, b) => a + b;// sum.js
console.log("sum.js is running");
module.exports = (a, b) => a + b;// app.js
require("./sum");
require("./sum");
require("./sum");// app.js
require("./sum");
require("./sum");
require("./sum");Output:
sum.js is runningsum.js is runningAfter the first require, Node.js caches the module and hands back the same module.exports object every time. Chapter 05: Diving in to NodeJS github repo explains the cache in detail.
Other things you'll see in CommonJS code
requirecan go anywhere, even inside anifor a function: it's an ordinary function call that runs when that line is reached.__dirnameand__filenamegive the current file's folder and path, e.g.path.join(__dirname, "data.json").- No top-level
await: wrap async startup code inasync function main() { ... }and callmain().
Common mistakes with CommonJS
exports = {...}instead ofmodule.exports = {...}: exports nothing.- Forgetting
./:require("sum")looks for a package calledsuminnode_modules, not your file. - Using
importin a CommonJS file:SyntaxError: Cannot use import statement outside a module. - Circular requires: if
a.jsrequiresb.jsandb.jsrequiresa.js, one of them gets a partially filledmodule.exports, so some values areundefined. Move shared code into a third module.
Key takeaways: CommonJS
- Share with
module.exports, bring in withrequire(). exportsis a shortcut to the same object: add properties to it, never reassign it.requirehandles files (extension optional), folders (index.js), JSON, core modules and packages.- Modules are cached: top-level code runs once.
Interview questions: CommonJS
Q1. What is the difference between module.exports and exports?
exports is a variable that initially points to the same object as module.exports. require() always returns module.exports. Adding properties through either works (exports.a = 1). But reassigning exports (exports = {...}) only changes the local variable and exports nothing. To export a single function or a new object, assign to module.exports.
Q2. What happens when you require a folder?
Node.js looks for a package.json with a "main" field in that folder. If there isn't one, it loads index.js. That's why an index.js that re-exports the folder's modules is a common pattern.
Q3. If you require the same module in five files, how many times does it run?
Once. The first require runs the file and stores the result in require.cache. Every later require of the same resolved path returns the same module.exports object without running the file again. So all five files share the same instance and its state.
Q4. What is a circular dependency in CommonJS, and why is it a problem?
It's when module A requires B and B requires A (directly or through others). Because CommonJS runs modules as they are required, one of them receives the other's module.exports before it's finished, so some exports are silently undefined. Fix it by moving the shared code into a third module, or by requiring lazily inside a function.
CommonJS vs ES Modules
Read this tab once you're comfortable with ES Modules: it shows how each CommonJS pattern translates, what really differs, and how the two systems work together in one project.
How Node.js decides which system a file uses
| File | Treated as |
|---|---|
.mjs | always an ES Module |
.cjs | always CommonJS |
.js | decided by the nearest package.json up the folder tree: "type": "module" → ES Module; "type": "commonjs" → CommonJS |
If there's no "type" at all, a .js file is CommonJS, unless it contains import/export syntax: since Node.js 22.12, Node then re-runs it as an ES Module and prints a MODULE_TYPELESS_PACKAGE_JSON warning. Always set "type" explicitly.
Cheat sheet: CommonJS → ES Modules
| What you want | CommonJS | ES Modules |
|---|---|---|
| export one main thing | module.exports = fn | export default fn |
| export several things | module.exports = { a, b } | export { a, b } |
| export while declaring | exports.a = ... | export const a = ... |
| import the main thing | const fn = require("./x") | import fn from "./x.js" |
| import some things | const { a, b } = require("./x") | import { a, b } from "./x.js" |
| import and rename | const { a: myA } = require("./x") | import { a as myA } from "./x.js" |
| import everything as an object | const x = require("./x") | import * as x from "./x.js" |
| just run a file | require("./setup") | import "./setup.js" |
| core module | const fs = require("node:fs") | import fs from "node:fs" |
| JSON file | require("./data.json") | import data from "./data.json" with { type: "json" } |
| folder | require("./calculate") | import ... from "./calculate/index.js" |
| load conditionally / later | if (x) require("a") | if (x) await import("a") |
| current folder | __dirname | import.meta.dirname |
What really differs
CommonJS (require) | ES Modules (import) | |
|---|---|---|
| Standard | Node.js-specific | official JavaScript standard (browsers, React, Deno, Bun...) |
| Loading | synchronous, runs when the require line is reached | imports found and linked before any code runs (can be async) |
| Where imports can go | anywhere, even inside if | static import only at the top level; import() anywhere |
| Imported values | what's in module.exports (destructuring copies values) | live, read-only bindings |
| File extension | optional (./sum) | required (./sum.js) |
Folder index.js | loaded automatically | never; write ./folder/index.js |
__dirname, __filename | available | import.meta.dirname / import.meta.filename |
Top-level await | not allowed | allowed |
| Strict mode | only with "use strict" | always on |
Top-level this | module.exports | undefined |
| Circular dependency | silently undefined values | ReferenceError (TDZ) |
| Tree-shaking by bundlers | hard (structure only known at runtime) | easy (structure known in advance) |
Copies vs live bindings
The same counter in both systems behaves differently:
// counter.cjs (CommonJS)
let count = 0;
module.exports = { count, increment() { count++; } };
// app.cjs
const { count, increment } = require("./counter.cjs");
increment();
console.log(count); // 0 ← a copy made when module.exports was built// counter.cjs (CommonJS)
let count = 0;
module.exports = { count, increment() { count++; } };
// app.cjs
const { count, increment } = require("./counter.cjs");
increment();
console.log(count); // 0 ← a copy made when module.exports was built// counter.js (ES Module)
export let count = 0;
export function increment() { count++; }
// app.js
import { count, increment } from "./counter.js";
increment();
console.log(count); // 1 ← the same variable// counter.js (ES Module)
export let count = 0;
export function increment() { count++; }
// app.js
import { count, increment } from "./counter.js";
increment();
console.log(count); // 1 ← the same variableMixing the two in one project
Your code may be ES Modules while some npm packages are still CommonJS (Express is one), or the other way round.
ES Module importing CommonJS: always works. The CommonJS file's module.exports becomes the default export. Node also detects most exports.x = ... / module.exports = { x } patterns, so named imports usually work too:
// app.js (ES Module)
import express from "express"; // express is CommonJS: module.exports → default
import counter, { count } from "./c.cjs"; // default = whole module.exports, plus detected names// app.js (ES Module)
import express from "express"; // express is CommonJS: module.exports → default
import counter, { count } from "./c.cjs"; // default = whole module.exports, plus detected namesCommonJS requiring an ES Module: works in Node.js 22.12+ (and 20.19+). require() returns the module's namespace object, so a default export is under .default:
// app.cjs
const logger = require("./logger.mjs");
logger.default("hi"); // the default export
const { calculateSum } = require("./sum.mjs"); // named exports work directly// app.cjs
const logger = require("./logger.mjs");
logger.default("hi"); // the default export
const { calculateSum } = require("./sum.mjs"); // named exports work directlyThe one exception: an ES Module that uses top-level await can't be required (ERR_REQUIRE_ASYNC_MODULE), because require must finish synchronously. Use await import() for those, which is also the only option on older Node.js versions. And if you ever need require inside an ES Module, createRequire(import.meta.url) from node:module makes one.
One more difference, about timing: at the top level of an ES Module, Promise callbacks run before process.nextTick callbacks, the opposite of CommonJS. Chapter 09 explains why.
Which should you use?
ES Modules for new code. They're the standard, the same syntax you use in React, and the ecosystem is moving there. Learn to read CommonJS for existing code: every require you meet has an ES Module equivalent in the cheat sheet above. In this course, the standalone examples use import; the DevTinder project in Season 2 uses require, following the original lectures.
Interview questions: CommonJS vs ES Modules
Q1. What are the main differences between CommonJS and ES Modules?
- Syntax:
require/module.exportsvsimport/export. - Standard: CommonJS is Node-specific; ESM is the official JavaScript standard, used by browsers and React too.
- Loading:
requireloads synchronously at the line where it's called; ESM finds and links all imports before running any code, so static imports must be at the top level. - Values:
requiregives you what's inmodule.exports(destructuring copies values); ESM gives live, read-only bindings. - ESM extras: top-level
await, strict mode always on,import.meta, easy tree-shaking. - CommonJS extras:
__dirname,__filename, automatic extensions andindex.jsresolution,requireanywhere.
Q2. How does Node.js decide whether a .js file is CommonJS or an ES Module?
It looks at the nearest package.json up the folder tree. "type": "module" → .js files are ES Modules; "type": "commonjs" → CommonJS. .mjs (always ESM) and .cjs (always CommonJS) override it. With no "type", a .js file is CommonJS, but since Node.js 22.12 a file containing import/export syntax is re-run as ESM with a warning. Best practice is to always set "type" explicitly.
Q3. Can an ES Module use require? Can a CommonJS file load an ES Module?
- ESM → CommonJS:
requireisn't defined in ESM, but you don't need it:import x from './file.cjs'works, withmodule.exportsas the default export (and most named exports detected automatically). If you really needrequire,createRequire(import.meta.url)fromnode:modulecreates one. - CommonJS → ESM: since Node.js 22.12 (and 20.19),
require('./file.mjs')works and returns the namespace object (default under.default), unless the module uses top-levelawait(ERR_REQUIRE_ASYNC_MODULE). Otherwise, and on older versions, useawait import('./file.mjs').
Q4. The same counter module prints 0 with require and 1 with import. Why?
With require, module.exports = { count } copies the value of count into an object when the module runs, and destructuring copies it again, so later changes inside the module aren't seen. With import, the name is a live binding to the module's own variable, so the importer always reads its current value.
Q5. How do you replace __dirname when moving code to ES Modules?
Use import.meta.dirname (and import.meta.filename instead of __filename), available since Node.js 20.11. They don't exist in ESM because __dirname and __filename are parameters of the CommonJS wrapper function, which ES Modules don't have.
What's next
In Chapter 05: Diving in to NodeJS github repo you'll look under the hood: how ES Modules are loaded in three phases, and how CommonJS uses a hidden function wrapper and five steps inside require.