skip to content

Specifier Resolution and Exports

How a bare specifier becomes a file on disk and how a package limits which files are reachable. Asked because the exports map breaks deep imports and is where dual packages get conditions wrong.

on this pageshow

explore

questions

5

In Node.js, how does `require()` turn a bare specifier such as `'some-package'` into a file on disk, and where does it look?

level: juniorimportance: must knowfreq 58%

answer

  1. built-ins before anything else
  2. start at the caller's directory
  3. climb parent node_modules folders
  4. exports first, then main, then probing
  5. require.resolve.paths shows the list

basics

~20 s

Built-in names win first. Otherwise Node checks the node_modules folder beside the calling file, then each parent's, up to the filesystem root, then NODE_PATH and global folders. In the package found, exports beats main; without exports, extensions and index files are probed.

solid answer

~40 s

If the name is a built-in such as `http`, `require()` returns the built-in. Otherwise Node starts at the **directory of the calling file**, not `process.cwd()`, and tries `<dir>/node_modules/some-package`, then the same in each parent directory up to the root, then any `NODE_PATH` entries and the global folders like `$HOME/.node_modules`. In the first folder that holds the package, an `"exports"` map decides the file outright. Without one, `"main"` is used, and a subpath like `some-package/lib/x` is tried as-is, then with `.js`, `.json` and `.node`, then as a folder with `index.js`. If nothing matches, it throws `MODULE_NOT_FOUND`. `require.resolve()` returns the chosen filename and `require.resolve.paths()` lists the folders searched.

code

javascript · 7 lines
javascript
// /srv/api/src/app.js (CommonJS)
console.log(require.resolve.paths('some-package'));
// [ '/srv/api/src/node_modules', '/srv/api/node_modules',
//   '/srv/node_modules', '/node_modules', ...NODE_PATH and global folders ]

console.log(require.resolve.paths('node:http')); // null: a built-in
console.log(require.resolve('some-package'));   // absolute path of the entry file

go deeper

for a junior

Recall the order: built-in names first, then node_modules folders from the calling file's directory upward, then NODE_PATH and global folders. Know that require.resolve shows the answer.

for a middle

Explain what happens inside the package folder: exports wins over main, and without exports Node probes .js, .json, .node and then index files. Mention MODULE_NOT_FOUND and require.resolve.paths.

for a senior

Use the walk to diagnose duplicate copies of a dependency, symlinked packages resolving from their real path, and NODE_PATH setups that break when code moves to import.

for a principal

Frame resolution as a source of production drift: which copy a file loads depends on the installed tree, so a lead pins how dependencies are laid out and bans NODE_PATH in services.

## What kind of specifier is it? A **specifier** is the string passed to `require()`. Node's CommonJS loader (the `require()` side of Node, as opposed to the ES module loader behind `import`) sorts it into one of four kinds before it touches the disk: | Specifier | Example | How it resolves | |---|---|---| | Built-in | `'fs'`, `'node:fs'` | Returned straight from the binary, no file lookup | | Relative or absolute | `'./db'`, `'../config'`, `'/opt/app/x'` | Resolved against the calling file's folder or the root | | Package import | `'#internal/db.js'` | Looked up in the nearest `package.json` `"imports"` map | | Bare | `'some-package'`, `'some-package/lib/x'` | The `node_modules` walk described below | Built-ins are checked first, so `require('http')` returns the built-in HTTP module even if a folder called `http` sits in `node_modules`. A few newer built-ins, such as `node:test` and `node:sqlite`, can only be required with the `node:` prefix, so they never collide with a package of the same name. ## The node_modules walk For a bare specifier, Node first checks whether the calling file's own package refers to itself by name (a self-reference, which only works when that package has an `"exports"` field). Then it walks upward. For a file at `/srv/api/src/routes/users.js` the search order is: 1. `/srv/api/src/routes/node_modules/some-package` 2. `/srv/api/src/node_modules/some-package` 3. `/srv/api/node_modules/some-package` 4. `/srv/node_modules/some-package` 5. `/node_modules/some-package` 6. each directory in `NODE_PATH`, then the **global folders** `$HOME/.node_modules`, `$HOME/.node_libraries` and `$PREFIX/lib/node` Two details matter. The walk starts from the **file that calls `require()`**, not from the working directory the process was started in. And Node never appends `node_modules` to a path segment that already is `node_modules`, so a dependency's own lookups start inside its folder and climb out through the parent `node_modules` trees. ## Inside the package folder Once a candidate folder exists, Node decides which file to load: - **`"exports"` present**: the map is the only authority. The subpath (`.` for the bare name, `./lib/x` for a deep import) must match a key or pattern, and the target is loaded exactly as written. No extension or index probing happens, and an unlisted subpath throws `ERR_PACKAGE_PATH_NOT_EXPORTED`. - **No `"exports"`, bare name**: `"main"` names the entry. If `"main"` is missing or does not resolve, Node falls back to `index.js`, then `index.json`, then `index.node`. - **No `"exports"`, deep subpath**: the path is tried as an exact file, then with `.js`, `.json` and `.node` appended, then as a folder (its own `package.json` `"main"`, then `index.*`). The extension list is short on purpose: `require('./x')` will find `x.js` but never `x.cjs` or `x.mjs`; those need the full name. ## Seeing what Node decided `require.resolve('some-package')` runs the same machinery without executing the module and returns the absolute filename, or throws `MODULE_NOT_FOUND`. `require.resolve.paths('some-package')` returns the array of folders it would search, or `null` for a built-in name. Both are the quickest way to explain "it works on my machine": they show which copy of a package a given file really gets. ## When nothing matches If every candidate fails, `require()` throws an `Error` whose `code` is `MODULE_NOT_FOUND`. The message names the specifier and, below it, a **require stack**: the chain of files whose `require()` calls led here, nearest first. ```plaintext Error: Cannot find module 'some-package' Require stack: - /srv/api/src/routes/users.js - /srv/api/src/app.js ``` The same list is on the error's `requireStack` property. Three causes cover most real cases: - the package is not installed in any `node_modules` folder above the calling file, often because a container image was built without it; - the code runs from a different folder than expected, so the walk never passes the folder that has the package; - the package exists, but its `"main"` points at a build output that was never generated. A package whose `"exports"` map refuses the subpath fails with `ERR_PACKAGE_PATH_NOT_EXPORTED` instead, which tells you the package was found and the map said no. ## Why this matters in a running service - **Nearest copy wins.** Two files in one app can load two different copies of a dependency when a nested `node_modules` holds another version. CommonJS caches by resolved filename, so those are two separate module instances. - **Symlinks resolve to the real path.** By default Node dereferences a symlinked package and searches for its dependencies from the real location; `--preserve-symlinks` changes that and changes the cache key with it. - **`NODE_PATH` is legacy.** It is still honoured by `require()`, but it is not part of resolving `import` specifiers, so code that relies on it breaks when it moves to ES modules. - **Global folders are historic.** They are searched last and are slower and less predictable than a local `node_modules`.

  • Why can two files in the same Node.js app get two different copies of one dependency?
    Because the walk starts at each caller's directory. If `node_modules/a/node_modules/dep` holds one version and the top-level `node_modules/dep` another, code inside `a` finds the nested copy first. CommonJS caches by resolved filename, so the two copies are separate instances with separate state, and `instanceof` checks across them fail. `require.resolve('dep')` from each file shows which path each gets.
  • What does `require('http')` load in Node.js if `node_modules` also contains a package named `http`?
    The built-in. Built-in names are checked before any file lookup, so the package is unreachable under that name. Writing `require('node:http')` makes the intent explicit and also bypasses `require.cache`. A few newer built-ins, such as `node:test` and `node:sqlite`, must be required with the prefix precisely so they never shadow existing packages.
  • How does a bare `import` in a Node.js ES module differ from this walk?
    The ES module resolver also climbs parent `node_modules` folders, but it ignores `NODE_PATH` and the global folders, and it stops at the first `node_modules/<name>` folder that exists instead of trying further parents. A deep subpath of a package without `"exports"` must also name the file with its extension, because the ES module resolver does no extension probing for it.

Looking for a book: you check the shelf in your own room, then the shelf in each room further out, and stop at the first shelf that has it. If the book has a table of contents, that, not your guess, decides which page you open.

  • require only looks in the node_modules folder at the project root
  • The search starts from process.cwd() rather than the calling file's folder
  • A package named http in node_modules overrides the built-in http module
  • require probes .js and index.js even for subpaths an exports map leaves out
  • NODE_PATH is searched before the local node_modules folders
  • require.resolve loads and runs the module to find its path
open as a page

In Node.js, why does `import './utils'` fail in an ES module when `require('./utils')` finds `utils.js` from CommonJS?

level: middleimportance: must knowfreq 55%

basics

~10 s

Node's ES module resolver resolves relative specifiers as URLs and never adds extensions or looks for index files, so './utils' must be written './utils.js'. A missing file throws ERR_MODULE_NOT_FOUND; a folder throws ERR_UNSUPPORTED_DIR_IMPORT.

open as a page

In Node.js, why does `require('my-package/lib/helpers')` throw `ERR_PACKAGE_PATH_NOT_EXPORTED` after the package adds an `exports` map in a minor release?

level: middleimportance: should knowfreq 45%

basics

~10 s

Once a package defines exports, Node resolves only the subpaths that map lists, with no extension or index probing. './lib/helpers' is not a key, so resolution throws ERR_PACKAGE_PATH_NOT_EXPORTED even though the file still exists.

open as a page

In a Node.js application, what does the package.json `imports` field do, and how does `import '#internal/db.js'` get resolved?

level: middleimportance: should knowfreq 25%

basics

~20 s

The imports field defines private, '#'-prefixed specifiers for code inside one package. Node finds the importing file's nearest package.json, matches '#internal/db.js' against its imports keys and patterns, and resolves the target from the package root, for both import and require().

open as a page

In Node.js conditional exports, how does the resolver choose between `import`, `require`, `node` and `default`, and why does key order in the object matter?

level: seniorimportance: should knowfreq 35%

basics

~20 s

Node walks the condition object's keys in their written order and takes the first whose name is active or is default. import is active for import and import(), require for require(), node always; so a default key written first wins for everyone.

open as a page