T8 Node.js · Lesson 2
Modules
A program of any size is built from parts. In Node, each file is a module: it keeps its own names to itself and offers only what it chooses. Share code with module.exports and require, the CommonJS way, or with export and import, the ES module way that browsers use too, and learn how Node finds the file you ask for.
- split a program into files, each a module with its own names
- share values with module.exports and load them with require
- avoid the exports trap, and know that a module runs only once
- say how require finds a file, a folder, JSON or a built-in module
- write ES modules with export and import, and run them in Node
- choose between the two kinds, and mix them safely
The back cover
A program of any size is built from parts, as a house is built from rooms. In Node, each file is a part of its own: it keeps its names to itself and offers others only what it chooses.
These pages show why programs are split into modules, and how require loads one and module.exports offers its parts. They show how Node finds the file a name points to. They also show the newer ES modules, with import and export, and how the two kinds can live together in one project.
Before you start
The story: A machine from parts
The Foreman unrolls a drawing as long as the hall: the new pump-house, every gear and valve on a single sheet. Nobody can find anything on it. When one valve was changed last week, three gears were redrawn by mistake.
The fitters stand around it, unsure where to begin. Each of them needs only a corner of the sheet, and each corner depends on another.
"A machine this size is never one drawing," says Foreman Tappet. "It is parts, each on a sheet of its own, each with a plate on its front that says what it offers. Build me the pump-house from parts."
Lesson 01 ran one file at a time. Real programs are many files: a few dozen for a small tool, thousands for a large server. Each file does one job and offers its work to the others. In Node, such a file is a module, and this lesson shows the two ways that Node lets modules share their work.
It builds on these ideas. Each one has a tiny example, so you can check that you remember it.
| What you already know | A tiny example | Where it comes back |
|---|---|---|
| Functions. | function read(name) { } | A module offers functions. |
| Objects. | { read, unit } | A module's offer is often an object. |
| Destructuring. | const { read } = gauge; | Taking out the parts you need. |
| Browser modules. | import { read } from "./gauge.js"; | The ES module way, in Node too. |
| Running a file. | node app.js | The program that loads the others. |
| __dirname. | /home/asha/shop | A module's own folder. |
| Relative paths. | ./tools/index.js | How a module names another. |
| JSON. | { "pressure": 3 } | Settings, loaded as a module. |
| Folders. | mkdir -p tools | A module can be a folder. |
| Errors with a code. | err.code | MODULE_NOT_FOUND, and its cousins. |
By the end of this lesson you will be able to:
- split a program into files, each a module with its own names;
- share values with module.exports and load them with require;
- avoid the exports trap, and know that a module runs only once;
- say how require finds a file, a folder, JSON or a built-in module;
- write ES modules with export and import, and run them in Node;
- choose between the two kinds, and mix them safely.
How to follow this lesson
A block may show several files. The last one, with the Run button, is the one you can edit; the files above it are written into the folder before it runs. Everything happens in the shop's folder, /home/asha/shop.
In one line
This lesson is about modules: files that keep their names to themselves and share only what they export, with require or with import.
Why programs are built from parts
At a glance
A kitchen is easier to run when the spices are in one cupboard and the plates in another. Code is the same: things that belong together are kept together.
In Node, each file is a module. The names made inside a file, its variables and functions, stay inside it, so two files can each have a total without clashing. A file offers others only what it puts on module.exports. Everything else is private, so a module can change its insides without breaking the files that use it.
Take a guess: How does Node keep a file's names private, when JavaScript itself has no such rule for scripts?
A program kept in one long file is the Foreman's drawing: everything is there, but nothing can be found, and a change in one place breaks another. The cure is to split it into modules: smaller files, each with one job, each offering only what the others need.
Node's documentation puts it in one sentence: in Node, each file is treated as a separate module. The first thing that follows is privacy. A name made in one file does not leak into another:
gauge.js
console.log(typeof secret);
app.js
const secret = "only in app.js";
console.log(typeof secret);
require("./gauge");
Terminal: node app.js
string
undefined
app.js made secret, then loaded gauge.js with require, which the next section explains. Inside gauge.js, secret does not exist: each module has its own names, as if each file were wrapped in a function of its own. In fact, that is how Node runs it.
Offering a part
A module shares something by putting it on module.exports, the module's plate: whatever is there is what other modules receive. Here gauge.js offers one function, and app.js uses it:
gauge.js
function read(name) {
return `${name}: 95 degrees`;
}
module.exports = { read };
app.js
const gauge = require("./gauge");
console.log(gauge.read("boiler"));
console.log(gauge);
Terminal: node app.js
boiler: 95 degrees
{ read: [Function: read] }
The function read lives in gauge.js, and app.js never needs to know how it works, only what it is called and what it gives back. If the gauge is rebuilt tomorrow, app.js is untouched, as long as read keeps its promise.
| One long file | Many modules |
|---|---|
| every name can clash with every other | each file keeps its own names |
| a change can break anything | a change stays inside one file, behind its exports |
| hard to test one part | each part can be tried alone |
| one person at a time | many people, each on their own files |
Worked example 1
The Engine Hall's report prints the boiler's and the pump's readings. Move the reading into a module of its own, gauge.js, so that other programs can use it too.
What we have: a reading function, wanted by more than one program
What we need: gauge.js offering read, and app.js using it twice
The plan: write read in gauge.js and put it on module.exports; in app.js, require it and call it
gauge.js
function read(name) {
return `${name}: 95 degrees`;
}
module.exports = { read };
app.js
const gauge = require("./gauge");
console.log(gauge.read("boiler"));
console.log(gauge.read("pump"));
Terminal: node app.js
boiler: 95 degrees
pump: 95 degrees
- app.js holds no reading code at all: it asks gauge.js. A second program could require gauge.js in the same way.
Both readings come from gauge.js.
Check: Change the text in gauge.js, and both lines change with it.
A path that fails: copying the read function into each program that needs it. The copies drift apart, and a fix in one never reaches the others.
When you are stuck: a name from another file is not defined
Each module keeps its own names: a name made in gauge.js is invisible in app.js.
Put what you want to share on module.exports in the file that makes it.
Then take it with require in the file that uses it.
Your turn
gauge.js makes const unit = "degrees" and exports nothing. Can app.js use unit after require("./gauge")?Tap to reveal
- What does each file keep to itself?
No: unit stays inside gauge.js unless it is exported.
Name two reasons to split a program into modules.Tap to reveal
- Think of names, and of changes.
Each file keeps its own names, and a change stays inside one file.
What is module.exports?Tap to reveal
- It is the module's plate.
What a module offers to the modules that load it.
Did you know?
Every file sits inside a function
Node keeps a file's names private with a trick. Its manual says that before a module's code runs, Node wraps it in a function with five parameters: exports, require, module, __filename and __dirname. Because the code runs inside that function, its top-level variables stay local to the module instead of becoming global. It is also where require and module come from.
Why it fits here: It answers this topic's question: Node wraps each file in a function, so its names stay inside.
Node's own modules are files too
The modules that come with Node are built the same way as yours. The Node manual says these built-in modules are compiled into the program, and are defined in Node's source, in its lib/ folder. Each page of the manual names its file: the page for fs begins with Source Code: lib/fs.js. Reading such a file shows how a large module is split into parts.
Why it fits here: It shows this topic's idea at full size: Node's own built-in modules are files in its lib/ folder.
Sources: Node.js manual: Modules (CommonJS); Node.js manual: File system
In one line
In Node, each file is a module: its names stay inside it, and only what it puts on module.exports is offered to other files.
Loading a module: require
At a glance
To use another file's parts, a module asks for them. In the CommonJS way, the asking is done with require.
require("./name") loads a module and gives back what it offers. The first time, Node runs the module's code; later requires of the same file run nothing and share the very same exports. In the file that node was asked to run, require.main === module is true, so a file can tell whether it was run directly or loaded by another.
Take a guess: What happens when two modules require each other?
The function require loads a module and gives back what it exported. Its argument names the file. A name that starts with ./ or ../ is a path from the folder of the file that calls require, and the ending .js may be left off:
gauge.js
exports.read = (name) => `${name}: ok`;
exports.unit = "degrees";
app.js
const { read, unit } = require("./gauge.js");
console.log(read("pump"), unit);
Terminal: node app.js
pump: ok degrees
Destructuring, from the modern JavaScript step, takes the two parts out of the exported object at once. This is the usual way to require: name only what you use.
A module runs once
The first require of a file runs it. Every later require of the same file gives back the same exports, without running the file again. Node's documentation says that modules are cached after the first time they are loaded:
counter.js
console.log("loading counter");
let count = 0;
module.exports = { add: () => ++count };
app.js
const a = require("./counter");
const b = require("./counter");
console.log(a.add(), b.add(), a === b);
Terminal: node app.js
loading counter
1 2 true
loading counter was printed once. a and b are the very same object, so the count is shared: the second add gives 2. This is useful: a module can hold one shared state, such as one set of settings or one open connection, for the whole program.
Run directly, or loaded?
Sometimes a file should do something when it is run with node, but not when another file requires it. require.main is the module that node was asked to run, and module is the current one:
gauge.js
console.log(require.main === module ? "run directly" : "required");
app.js
require("./gauge");
Terminal: node gauge.js
node app.js
run directly
required
| Expression | Gives |
|---|---|
require("./gauge") | gauge.js's exports; the file runs on the first require only |
const { read } = require("./gauge") | only the part you need |
require.main === module | true when this file was run with node |
Worked example 2
Two parts of the pump-house both need the hall's pressure limit. Keep it in one module, and show that both parts see the same value after one of them changes it.
What we have: a limit of 3, read by two modules
What we need: one shared value
The plan: settings.js exports an object; valve.js and pump.js both require it; one changes it, the other reads it
settings.js
module.exports = { limit: 3 };
valve.js
const settings = require("./settings");
exports.raise = () => { settings.limit += 1; };
pump.js
const settings = require("./settings");
exports.limit = () => settings.limit;
app.js
const valve = require("./valve");
const pump = require("./pump");
valve.raise();
console.log(pump.limit());
Terminal: node app.js
4
- settings.js ran once, so valve.js and pump.js hold the same object. The valve raised the limit to 4, and the pump read 4.
The pump reads 4: one settings object, shared.
Check: Print settings from app.js too: it also shows limit: 4.
A path that fails: giving each module its own copy, with const limit = 3 in each. The valve would raise its own copy, and the pump would still read 3.
When you are stuck: a module seems to run only once, or to share a value you did not expect
That is the cache: the first require runs the file, later ones return the same exports.
If each user needs its own value, export a function that makes one, and call it.
A console.log at the top of the module shows when it really runs.
Your turn
counter.js prints loading. app.js requires it three times. How many times is loading printed?Tap to reveal
- What does the cache keep?
Once.
What is the difference between require("./gauge") and require("gauge")?Tap to reveal
- Which one is a path?
./gauge is a file next to the caller; gauge is looked up as a package or built-in.
node -p 'require.main === undefined'
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
true
- With -p there is no main file.
It prints true.
Did you know?
Half-finished exports
Two modules may require each other, and then one sees the other half done. The Node manual says that with circular require calls, a module might not have finished running when it is returned. In its example, a.js requires b.js, and b.js requires a.js back: b.js then receives an unfinished copy of a.js's exports, with only what a.js had set so far.
Why it fits here: It answers this topic's question: in a circle of requires, one module gets the other's exports half finished.
Reloading from the cache
The cache behind require is an object you can reach. The Node manual says modules are cached in require.cache when they are required, and that deleting a key from it makes the next require load the module afresh. That does not apply to native addons, for which reloading gives an error. Tools that reload code while it runs work this way.
Why it fits here: It adds to this topic's run-once rule: deleting a module's entry in require.cache makes the next require run it again.
In one line
require("./name") loads a module, running it the first time only, and gives back its exports; later requires share the same exports. require.main === module is true in the file that node was asked to run.
What a module offers: module.exports and exports
At a glance
A module decides what to offer by what it puts on module.exports. require gives back exactly that.
module.exports can hold an object full of functions, a single function, a class or any other value. The name exports is a shortcut that points at the same object, so exports.total = total adds to it. But never give exports itself a new value: that cuts the link, and the new value is offered to nobody. When in doubt, assign to module.exports and nothing else.
Take a guess: Can a module set module.exports later, inside a timer?
A module can offer anything: an object of several parts, one function, a class, a number. Whatever module.exports holds when the file finishes is what require gives back. Giving module.exports a new value offers that value alone:
gauge.js
module.exports = function read(name) {
return `${name}: 40 degrees`;
};
app.js
const read = require("./gauge");
console.log(read("press"));
Terminal: node app.js
press: 40 degrees
The shortcut, and its trap
Node also gives each module a name exports, which at the start points to the same object as module.exports. Adding properties to it adds them to module.exports, so this is a shorter way to offer several parts:
gauge.js
exports.read = (name) => `${name}: ok`;
exports.unit = "degrees";
app.js
const gauge = require("./gauge");
console.log(gauge);
Terminal: node app.js
{ read: [Function (anonymous)], unit: 'degrees' }
The trap is to give exports a new value. That only points the local name somewhere else; module.exports, the plate that require reads, is left empty:
gauge.js
exports = { read: () => "lost" };
app.js
const gauge = require("./gauge");
console.log(gauge, typeof gauge.read);
Terminal: node app.js
{} undefined
Node's documentation warns about exactly this. The rule that avoids it is short: add to exports with a dot, as in exports.read = ...; to offer a single new value, assign to module.exports itself.
| In the module | require gives |
|---|---|
module.exports = { read, unit }; | the object |
module.exports = read; | the function itself |
exports.read = read; | an object with read on it |
exports = { read }; | an empty object: the trap |
Worked example 3
valve.js must offer two functions, open and close, and app.js must use both. Write valve.js with the exports shortcut, the safe way.
What we have: two functions to offer
What we need: an object with open and close
The plan: exports.open = ...; exports.close = ...; in app.js, destructure both
valve.js
exports.open = () => "open";
exports.close = () => "close";
app.js
const { open, close } = require("./valve");
console.log(open(), close());
Terminal: node app.js
open close
- Each line adds a property to the object that module.exports holds, so require gives back both.
app.js prints open close.
Check: console.log(require("./valve")) shows both functions.
A path that fails: exports = { open, close }. The object is made, but module.exports stays empty, and destructuring gives two undefined values.
When you are stuck: require gives back an empty object
Look for exports = in the module: that rebinds the local name only.
Use module.exports = for a new value, or exports.name = for each part.
Check that the module assigns its exports at its top level, not later inside a timer.
Your turn
gauge.js holds only module.exports = 42. What does require("./gauge") give?Tap to reveal
- module.exports holds a number.
42.
Why does exports = { read } offer nothing?Tap to reveal
- Which object does require read?
It rebinds the local name only; module.exports stays empty.
Rewrite exports = { unit: "degrees" } so that it works.Tap to reveal
- Use a dot, or module.exports.
exports.unit = "degrees";, or module.exports = { unit: "degrees" };.
Did you know?
Too late in a timer
What a module offers must be settled straight away. The Node manual says assignment to module.exports must be done immediately, and cannot be done in any callbacks. Its example sets module.exports inside a timer of 0 milliseconds; the file that requires it has already received the old exports, so its value a is undefined.
Why it fits here: It answers this topic's question: module.exports must be set at once, as a timer would set it after require has returned.
A module that offers a class
A module can offer a single class instead of an object. Node's own events module does: its manual says all objects that emit events are instances of the EventEmitter class, and its examples load that class with const EventEmitter = require('node:events'). What comes back is the class itself, ready for new or for extends, because the class is what module.exports holds.
Why it fits here: It shows this topic's any-value rule in Node itself: require('node:events') gives back the EventEmitter class.
Source: Node.js manual: Events
In one line
require gives back whatever module.exports holds: an object, a function or any value. exports is a shortcut to the same object; add to it with a dot, but never assign it a new value.
How require finds a module
At a glance
require("./orders") names no file exactly. Node has to work out which file is meant.
From the folder of the file that called it, Node tries the name as written, then with .js, then with .json, and then a folder's index.js. A JSON file is read and parsed into an object. A name such as node:fs, with no path, is a built-in module. If nothing matches, require throws MODULE_NOT_FOUND, with the require stack that led there. The stack shows which file asked.
Take a guess: Are some of Node's built-in modules reachable only with the node: prefix?
require looks in a fixed order. For a path such as ./gauge, it tries the name exactly, then with .js, then with .json added; if the name is a folder, it loads the folder's index.js. So a whole folder can be one module, with index.js as its front door:
tools/index.js
module.exports = "the toolbox";
app.js
console.log(require("./tools"));
Terminal: node app.js
the toolbox
JSON files
A .json file is read as data: require gives back the parsed value, so settings can live in a file of their own, with no code at all:
settings.json
{ "engine": "main", "pressure": 3 }
app.js
const settings = require("./settings.json");
console.log(settings, settings.pressure * 2);
Terminal: node app.js
{ engine: 'main', pressure: 3 } 6
Built-in modules
A name that is not a path is looked for among Node's built-in modules first: fs for files, path for paths, os for the computer, and many more. Writing node: in front makes it plain that you mean the built-in one:
app.js
const path = require("node:path");
const os = require("os");
console.log(path.join("logs", "today.txt"), os.EOL === "\n");
console.log(typeof require("node:fs").readFileSync);
Terminal: node app.js
logs/today.txt true
function
path.join joins parts of a path with the right separator, and os.EOL is the end of a line on this computer, \n on Linux. Names without ./ and not built in are packages, the subject of the next lesson.
When nothing is found
If no file matches, require throws an error whose code is MODULE_NOT_FOUND, with the list of files that asked for it:
app.js
try {
require("./gauge");
} catch (e) {
console.log(e.code);
console.log(e.message);
}
Terminal: node app.js
MODULE_NOT_FOUND
Cannot find module './gauge'
Require stack:
- /home/asha/shop/app.js
The Require stack says who asked: app.js. In a big program, that list points to the file with the wrong path.
| require(...) | Looks for |
|---|---|
"./gauge" | gauge, gauge.js, gauge.json, then gauge/index.js, next to the caller |
"./settings.json" | that file, read as JSON |
"node:fs", "fs" | the built-in module |
"express" | a package, in node_modules (the next lesson) |
Worked example 4
The pump-house keeps its parts in a folder, parts/, with valve.js inside. Make the folder load as one module, so that app.js can write require("./parts").
What we have: parts/valve.js, offering open
What we need: require("./parts") giving the valve's open
The plan: an index.js in the folder that requires the valve and passes it on
parts/valve.js
exports.open = () => "open";
parts/index.js
exports.valve = require("./valve");
app.js
const parts = require("./parts");
console.log(parts.valve.open());
Terminal: node app.js
open
- require("./parts") found the folder and loaded its index.js, which loaded ./valve from inside the folder: each path starts from the file that writes it.
app.js reaches the valve through parts/index.js.
Check: Add parts/pump.js and one more line to index.js: app.js gets parts.pump too.
A path that fails: require("./parts/valve") from parts/index.js. That path starts from parts/, so it looks for parts/parts/valve.js, and fails.
When you are stuck: require says Cannot find module
Read the path in the message, and the Require stack: the last file listed made the call.
A path starts from the folder of the file that calls require, not from where you typed node.
ls the folder: check the name, the ending, and whether it is a folder without an index.js.
Your turn
app.js calls require("./data"), and the folder holds only data.json. What does require load?Tap to reveal
- It tries .js, then .json.
data.json, parsed.
What does require("./tools") load when tools is a folder?Tap to reveal
- The front door of a folder.
tools/index.js.
node -p 'require("node:path").join("a", "b", "c.txt")'
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
a/b/c.txt
- path.join joins the parts with /.
It prints a/b/c.txt.
Did you know?
Modules only with node:
Some built-in modules answer only to the node: prefix. The Node manual says that a built-in name with node: always gives the built-in module, and bypasses the require cache. It lists the modules that require the prefix: node:ffi, node:sea, node:sqlite, node:test and node:test/reporters. So require('node:test') loads Node's test runner, while a bare require('test') looks for a package of that name.
Why it fits here: It answers this topic's question: modules such as node:test and node:sqlite can only be loaded with the node: prefix.
A fourth ending: .node
require's list of endings has one more after .js and .json. The Node manual's step-by-step search says that if X.node is a file, it is loaded as a binary addon. Such addons are compiled code, often written in C or C++, that Node loads like any module. That is how some packages reach speeds or system features that JavaScript alone cannot.
Why it fits here: It completes this topic's search order: after .js and .json, require also tries .node, a compiled binary addon.
Sources: Node.js manual: Modules (CommonJS); Node.js manual: C++ addons
In one line
require("./name") tries the name, then .js and .json, then a folder's index.js, from the caller's folder; JSON is parsed; node:fs and other names are built-ins. A miss throws MODULE_NOT_FOUND with the Require stack.
ES modules in Node: import and export
At a glance
JavaScript later gained a module system of its own, written into the language: ES modules, with import and export.
A module offers with export and loads with import, and every path to a file needs its ending, as in import { total } from "./sum.js". Node reads .mjs files this way, and .js files when package.json says "type": "module". In an ES module, import.meta.dirname replaces __dirname, and await works at the top level. Modern browsers understand exactly the same syntax.
Take a guess: Can Node run a TypeScript file directly, with no build step?
require and module.exports are Node's older way, called CommonJS. The modern JavaScript step taught the language's own way, ES modules, with export and import; Node's documentation calls them the official standard format. Node runs them too. The simplest sign is the ending .mjs:
gauge.mjs
export function read(name) {
return `${name}: 95`;
}
export const unit = "degrees";
export default "the gauge";
app.mjs
import gauge, { read, unit } from "./gauge.mjs";
console.log(gauge, read("boiler"), unit);
Terminal: node app.mjs
the gauge boiler: 95 degrees
export before a function or a const offers it by name; export default offers one main value. import takes the default first, then named parts in braces, exactly as in the browser.
Telling Node which kind a file is
Node decides for each file. A .mjs file is an ES module and a .cjs file is CommonJS. For a .js file, Node reads the nearest package.json: "type": "module" makes .js files ES modules. A package.json is a project's own file of settings, the subject of the next lesson:
package.json
{ "type": "module" }
gauge.js
export const read = () => "esm gauge";
app.js
import { read } from "./gauge.js";
console.log(read());
Terminal: node app.js
esm gauge
With no marker at all, Node 22 looks at the code itself, and runs it as an ES module if it uses import or export. Do not rely on that: Node warns about it when a package.json says nothing, and a reader cannot tell. Say what you mean with .mjs or "type".
What is different inside an ES module
Three things change. A relative import must give the file's ending: ./gauge.mjs, never ./gauge. There is no require, module, __dirname or __filename; import.meta.dirname and import.meta.filename take their place. And await may be used at the top level, outside any function:
app.mjs
const wait = (ms) => new Promise((r) => setTimeout(r, ms));
await wait(100);
console.log("top-level await works");
console.log(typeof require, typeof module, import.meta.dirname, import.meta.filename);
Terminal: node app.mjs
top-level await works
undefined undefined /home/asha/shop /home/asha/shop/app.mjs
Built-in modules are imported the same way, as a default or by name:
app.mjs
import fs from "node:fs";
import { join } from "node:path";
console.log(typeof fs.readFileSync, join("a", "b"));
Terminal: node app.mjs
function a/b
ES modules also keep live bindings: an imported name always shows the exporting module's current value, which CommonJS's copied values do not:
lib.mjs
export let count = 0;
export function add() { count++; }
app.mjs
import { count, add } from "./lib.mjs";
add();
add();
console.log(count);
Terminal: node app.mjs
2
| CommonJS | ES module | |
|---|---|---|
| offer | module.exports = ..., exports.x = ... | export ..., export default ... |
| load | const x = require("./x") | import x from "./x.mjs" |
| file ending in a path | may be left off | must be given |
| the file's folder | __dirname | import.meta.dirname |
| await at the top level | no | yes |
| marked by | .cjs, or .js with no "type" | .mjs, or .js with "type": "module" |
Worked example 5
Write the gauge as an ES module that offers read by name and the unit as its default, and use both from an ES module app.
What we have: a gauge to share
What we need: gauge.mjs with a named and a default export, and app.mjs using both
The plan: export function read; export default the unit; import unit, { read } with the full file name
gauge.mjs
export function read(name) {
return `${name}: 95`;
}
export default "degrees";
app.mjs
import unit, { read } from "./gauge.mjs";
console.log(read("pump"), unit);
Terminal: node app.mjs
pump: 95 degrees
- The default can be named anything on import; here it is unit. The named export must be imported by its own name, read.
app.mjs prints pump: 95 degrees.
Check: import whatever, { read } from "./gauge.mjs" works the same: a default has no fixed name.
A path that fails: import { read } from "./gauge". In an ES module the ending is required, and Node stops with ERR_MODULE_NOT_FOUND.
When you are stuck: an ES module will not load
Check the ending in every relative import: ./gauge.mjs, not ./gauge.
Check how Node reads the file: .mjs, or "type": "module" in package.json for .js files.
Replace __dirname with import.meta.dirname, and require with import.
Your turn
In an ES module, what takes the place of __dirname?Tap to reveal
- It hangs off import.meta.
import.meta.dirname.
Which marker makes every .js file in a project an ES module?Tap to reveal
- It goes in package.json.
"type": "module".
node -p 'typeof import.meta' 2>/dev/null || echo failed
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
failed
- -p runs its code as CommonJS.
- import.meta exists only in an ES module.
It prints failed.
Did you know?
TypeScript, with the types wiped out
Node can now run TypeScript files itself. Its manual says that by default Node executes TypeScript files that contain only erasable TypeScript syntax: it replaces that syntax with whitespace, and performs no type checking. Type stripping was added in Node 22.6.0, became the default in 23.6.0 and 22.18.0, and became stable in 25.2.0 and 24.12.0.
Why it fits here: It answers this topic's question: Node runs simple TypeScript files directly, by wiping out the types, though it checks none of them.
Node can guess the module kind
A .js file with no type field need not fail when it uses import. The Node manual describes syntax detection: Node inspects the source of an ambiguous file to see whether it holds ES module syntax, and if it does, treats it as an ES module. Added in Node 21.1.0 and 20.10.0, it has been on by default since 22.7.0 and 20.19.0. Setting the type field is still clearer.
Why it fits here: It adds to this topic's type field: Node can detect import and export in an ambiguous .js file and load it as an ES module.
In one line
ES modules offer with export and load with import, with the file ending in every path. Node reads .mjs files, and .js files under "type": "module", this way; import.meta.dirname replaces __dirname, and await works at the top level.
Choosing, and mixing the two
At a glance
Many projects hold both kinds of module, old files in CommonJS and new ones as ES modules. They can work together, with care.
An ES module can import a CommonJS file, which arrives as its default export: take what you need from it rather than rely on named imports. A CommonJS file can load an ES module with import(), which gives back a promise. In a new project, pick one kind and keep to it, ideally ES modules, the kind the language itself defines.
Take a guess: Can a CommonJS file now load an ES module with plain require?
Both kinds are everywhere. Older Node code and many packages are CommonJS; new code, and code shared with browsers, is usually ES modules. A program can use both, with one rule to remember: an ES module can import a CommonJS file, and gets its module.exports as the default export:
gauge.js
module.exports = { read: () => "cjs" };
app.mjs
import gauge from "./gauge.js";
console.log(gauge.read());
Terminal: node app.mjs
cjs
Named imports from CommonJS work only when Node can find the names by reading the file, and its documentation says that this does not always succeed. Here it fails:
gauge.js
module.exports = { read: () => "cjs" };
app.mjs
import { read } from "./gauge.js";
console.log(read());
Terminal: node app.mjs
echo "[$?]"
file:///home/asha/shop/app.mjs:1
import { read } from "./gauge.js";
^^^^
SyntaxError: Named export 'read' not found. The requested module './gauge.js' is a CommonJS module, which may not support all module.exports as named exports.
CommonJS modules can always be imported via the default export, for example using:
import pkg from './gauge.js';
const { read } = pkg;
at ModuleJob._instantiate (node:internal/modules/esm/module_job:226:21)
at async ModuleJob.run (node:internal/modules/esm/module_job:335:5)
at async onImport.tracePromise.__proto__ (node:internal/modules/esm/loader:681:26)
at async asyncRunEntryPointWithESMLoader (node:internal/modules/run_main:117:5)
Node.js v22.23.1
[1]
Node's own message gives the cure: import the default, then destructure it. The address in the first line, file:///home/asha/shop/app.mjs, is the file written as a URL, the way ES modules name files.
Going the other way, from a CommonJS file to an ES module, is harder, because an ES module may wait with top-level await; a CommonJS file can load one with the asynchronous import() function, which gives a promise:
gauge.mjs
export const read = () => "esm";
export default "the gauge";
app.js
import("./gauge.mjs").then((gauge) => console.log(gauge.default, gauge.read()));
Terminal: node app.js
the gauge esm
| You are in | To load CommonJS | To load an ES module |
|---|---|---|
| CommonJS | require("./x.js") | await import("./x.mjs"), in an async function |
| an ES module | import x from "./x.js" (the default) | import { a } from "./x.mjs" |
Which to choose
For a new project, choose one kind and keep to it. ES modules are the language's own standard and work in browsers too; set "type": "module" in package.json and use import everywhere. When you join an existing project, follow what its package.json and files already do.
Worked example 6
An ES module app must use an old CommonJS gauge that exports read and unit on one object. Load it the way that always works.
What we have: gauge.js, CommonJS, with module.exports = { read, unit }
What we need: read and unit in app.mjs
The plan: import the default, then destructure it, as Node's message advises
gauge.js
module.exports = { read: () => "cjs", unit: "degrees" };
app.mjs
import gauge from "./gauge.js";
const { read, unit } = gauge;
console.log(read(), unit);
Terminal: node app.mjs
cjs degrees
- The default import is the whole module.exports object, so destructuring it never depends on Node reading the file's names.
app.mjs prints cjs degrees.
Check: The same lines work whatever style gauge.js uses inside.
A path that fails: import { read, unit } from "./gauge.js". Whether it works depends on how gauge.js is written, and here Node finds no named exports.
When you are stuck: an import from a CommonJS file fails with Named export not found
Import the default instead: import pkg from "./file.js".
Then take the parts out: const { a, b } = pkg.
In a CommonJS file, load an ES module with import(), which gives a promise.
Your turn
What does import gauge from "./gauge.js" give, when gauge.js is CommonJS?Tap to reveal
- Which object does a CommonJS file offer?
Its module.exports.
How does a CommonJS file load an ES module?Tap to reveal
- require cannot wait.
With import(), which gives a promise.
You start a new project. Which kind of module should it use, and how do you say so?Tap to reveal
- The language's own standard.
ES modules, with "type": "module" in package.json.
Did you know?
require can load ES modules now
The wall between the two kinds is lower than it was. The Node manual says require() can load ES modules, a feature added in Node 22.0.0 and 20.17.0. It stopped printing an experimental warning by default in 23.5.0, 22.13.0 and 20.19.0, and is no longer experimental since 25.4.0. So a CommonJS file can often require an ES module directly, without import().
Why it fits here: It answers this topic's question: recent versions of Node let require load an ES module directly.
require inside an ES module
An ES module has no require of its own, but it can make one. The Node manual describes createRequire in the node:module module, added in Node 12.2.0. Its example imports createRequire, then writes const require = createRequire(import.meta.url), and uses that require to load a CommonJS file next to it.
Why it fits here: It adds the other direction to this topic's mixing: createRequire gives an ES module a require of its own.
In one line
An ES module imports a CommonJS file as its default export; destructure it rather than rely on named imports. A CommonJS file loads an ES module with import(). In a new project, pick one kind, ideally ES modules.
Where it is used
Every Node program beyond a few lines is built from modules. Here is where each idea of this lesson does its work.
| What you learned | Where it is used | A real example |
|---|---|---|
| one file, one job | every project's folder of source files | routes.js, database.js and server.js in a web server |
| module.exports and require | older projects and many packages | a project written before ES modules came to Node |
| the module cache | one shared connection or set of settings | a database module that connects once for the whole program |
| folders with index.js | grouping parts behind one name | require("./models") loading every model |
| JSON modules | settings kept out of the code | require("./config.json") |
| ES modules | new projects, and code shared with browsers | "type": "module" in a new project's package.json |
| built-in modules | files, paths, the network | node:fs, node:path and node:http, in the next lessons |
The pattern is the Engine Hall's: each part on its own sheet, with a plate that says what it offers, so that a change to one part never redraws the others.
Mistakes and debugging
These are the slips that people meet most often with modules. Every output below is the real one, from the code shown.
1. A path without ./
gauge.js
module.exports = 1;
app.js
try {
require("gauge");
} catch (e) {
console.log(e.code);
}
Terminal: node app.js
MODULE_NOT_FOUND
Without ./, require looks for a built-in or a package called gauge, not the file beside you. The fix: require("./gauge").
2. Giving exports a new value
valve.js
exports = { open: () => "open" };
app.js
const { open } = require("./valve");
console.log(typeof open);
Terminal: node app.js
undefined
The object went to the local name only. The fix: module.exports = { open };, or exports.open = ....
3. Leaving off the ending in an ES module
gauge.mjs
export const read = () => "ok";
app.mjs
import { read } from "./gauge";
Terminal: node app.mjs 2>&1 | grep -o 'Cannot find module.*'
Cannot find module '/home/asha/shop/gauge' imported from /home/asha/shop/app.mjs
An ES module needs the whole file name. The fix: import { read } from "./gauge.mjs";.
4. Using __dirname in an ES module
app.mjs
console.log(typeof __dirname, import.meta.dirname);
Terminal: node app.mjs
undefined /home/asha/shop
__dirname belongs to CommonJS. The fix: import.meta.dirname, as the block shows.
5. Expecting a module to run each time
bell.js
console.log("the bell rings");
app.js
require("./bell");
require("./bell");
Terminal: node app.js
the bell rings
The second require came from the cache, so the bell rang once. The fix: export a function, module.exports = () => console.log(...), and call it each time you need it.
The debugging corner: what did that module give me?
Print it: console.log(require("./gauge")) shows exactly what module.exports held. In an ES module, import * as gauge from "./gauge.mjs" and console.log(gauge) show every export. An error's code, MODULE_NOT_FOUND or ERR_MODULE_NOT_FOUND, and the path in its message point to the file that was not found.
Quick card
The whole lesson on one card. Come back to it whenever you need a reminder.
gauge.mjs
export const read = (name) => `${name}: 95`;
export default "the gauge";
settings.js
module.exports = { limit: 3 }; // CommonJS: module.exports, loaded with require
app.mjs
import gauge, { read } from "./gauge.mjs"; // an ES module: the default, then names
import settings from "./settings.js"; // CommonJS, as the default export
import { join } from "node:path"; // a built-in
console.log(gauge, read("pump"), settings.limit, join("logs", "a.txt"));
console.log(import.meta.dirname); // the file's folder
Terminal: node app.mjs
the gauge pump: 95 3 logs/a.txt
/home/asha/shop
| When you see | It means | Do |
|---|---|---|
Cannot find module './x' with a Require stack | no such file, from the caller's folder | check the path, starting with ./ |
{} from require | exports was given a new value | module.exports = ... |
ERR_MODULE_NOT_FOUND | an ES module could not find a file | give the whole name, ending included |
Named export 'x' not found | a named import from a CommonJS file | import the default, then destructure it |
__dirname is undefined | it is an ES module | import.meta.dirname |
| a module's code runs only once | the module cache | export a function, and call it |
The story: Parts that fit
You cut the drawing into parts: a gauge, a valve and a pump, each on its own sheet, each offering only what the others need, through the plate on its front. The pump-house is put together from them in one afternoon.
When the valve changes next week, only its sheet is redrawn, and every part that uses it gets the new valve at once, with nothing else touched.
The Foreman bolts on the last plate. "Next," she says, "parts that other halls have made."
Reagents gathered: module, module.exports, require, ES module, import, export.
Sources
- The Node.js documentation (Not stated for the docs in the Node.js LICENSE file (read 2026-10-26); facts and ideas only)
- MDN Web Docs (Prose CC BY-SA 2.5 or later; code samples added since 2010-08-20 CC0 (its licensing page, read 2026-10-26); reused with credit)