How Node resolves modules

Intermediate · 6 min

How require and import find a file, from built-ins and relative paths to the node_modules walk, index files, main and exports.

Before thisCommonJS modulesES modules in Node and interop

Programming with Mosh · 6 min

How Node resolves modules

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Programming with MoshReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • Resolution starts from the shape of the specifier: a built-in name (`fs`, `node:fs`), a relative or absolute path (`./x`, `/x`), or a bare package name (`express`, `@scope/pkg`). Each is looked up differently.
  • Use the `node:` prefix for built-ins. It is unambiguous, it cannot be shadowed by an npm package of the same name, and some built-ins (`node:test`, `node:sqlite`) only exist with the prefix.
  • For a bare name, Node looks in `./node_modules`, then `../node_modules`, then the parent's, all the way up to the file-system root. The nearest match wins, which is how two versions of a package can coexist.
  • Inside a package directory, the entry point is the `exports` field if present, otherwise `main`, otherwise `index.js`. When `exports` exists, it also blocks deep imports of any path it does not list.
  • CommonJS relative paths may omit the extension (Node tries `.js`, `.json`, `.node`, then a folder's `index.js`). ES module relative imports must include it.

The question behind every import

When you write require('express') or import './utils.js', Node has a string and must produce a file. It has to answer questions like: is this a built-in? A path? A package, and if so, which copy of it, and which file inside it? The rules are short, and knowing them turns “Cannot find module” from a mystery into a five-minute fix.

Step one: what kind of specifier is it?

Node classifies the string by how it starts:

  1. Built-in: fs, node:fs, node:test. Built-ins win over everything else.
  2. Relative or absolute path: starts with ./, ../ or /. It is resolved against the requiring file’s directory.
  3. Bare name: anything else, like express or @scope/tool. It is a package, and Node searches node_modules directories.
  4. Private import: starts with #. It looks in the package’s own imports field.

Prefer the node: prefix for built-ins. It makes the intent explicit, it cannot be hijacked by an npm package called fs or path, and some modules exist only in prefixed form. You can check:

const { isBuiltin } = require('node:module');
console.log(isBuiltin('fs'), isBuiltin('node:fs'));   // true true
try { require('test'); } catch (e) { console.log(e.code); }   // MODULE_NOT_FOUND
console.log(typeof require('node:test').test);                 // function

Relative paths and the extension rule

For require('./util') in CommonJS, Node tries in order:

  1. the exact file ./util
  2. ./util.js, ./util.json, ./util.node
  3. a directory ./util: its package.json main, otherwise ./util/index.js

So require('./cfg') loads cfg.json and returns the parsed object, and require('./util') can find util/index.js. This leniency is a CommonJS feature. ES modules do not do it: import './util' fails, and you must write ./util.js (see ES modules in Node and interop).

Bare names: the node_modules walk

For require('pkg') from /project/src/app.js, Node looks in this order and uses the first hit:

/project/src/node_modules/pkg
/project/node_modules/pkg
/node_modules/pkg

You can see the real list for any file with module.paths, and ask for a specific resolution with require.resolve:

console.log(module.paths.slice(0, 2));
console.log(require.resolve('pkg'));         // absolute path of the file that would load
console.log(require.resolve.paths('pkg'));   // the directories searched

Because the nearest copy wins, a package can ship its own private version of a dependency in its own node_modules, and the rest of your tree never sees it. This is how npm can keep two incompatible versions of the same library installed side by side. In a test with node_modules/dupe at the top level and another in src/node_modules, a require('dupe') from src loads the inner one.

Two older mechanisms exist beyond the walk. The NODE_PATH environment variable adds extra directories (it worked in a test, but it is considered legacy), and there are global folders in the user’s home directory kept for compatibility. Do not rely on either in new projects. Symbolic links, as npm workspaces use them, are resolved to their real path before the search, which is why linked packages find their own dependencies; see npm workspaces and monorepos.

Inside the package: exports, main, index.js

Once Node has found node_modules/pkg, it needs a file inside it. It reads package.json in that folder:

  1. If there is an exports field, use it. It defines exactly what can be imported, can vary by import versus require, and blocks every path it does not list.
  2. Otherwise use main.
  3. Otherwise use index.js.

With both main: "./lib/entry.js" and exports: { ".": "./lib/other.js" } present, require('pkg') returned the exports target in a test, so main was ignored. exports also means require('pkg/lib/entry.js') throws ERR_PACKAGE_PATH_NOT_EXPORTED. Deep imports used to be an accident of the folder layout; now the package author decides. The full field is the subject of package.json fields and exports.

Debugging “Cannot find module”

In order of frequency:

  • Typo, or the dependency is not in package.json and happened to be installed by something else. Run npm ls <name>.
  • You are running from the wrong directory, so the walk-up never reaches the node_modules that holds it.
  • A relative import in ESM without the extension.
  • The package’s exports does not expose the path you are importing (ERR_PACKAGE_PATH_NOT_EXPORTED, a different error).
  • A built-in written without its required node: prefix.

Printing require.resolve.paths('name') shows where Node actually looked.

What the video covers

Mosh’s six-minute video, from 2018, is about loading a module with require: the relative-path syntax and how Node finds a file. This is the weakest pick in the group. It does not cover the node_modules walk, exports, or the node: prefix according to its title and description, and no transcript was available. The sections on the walk, the extension rules and package entry points are the lesson’s own, and the commands were run on Node 26.13.1. No better single video on resolution turned up.

Where this fits

Resolution is the reason package layout matters. Package.json fields and exports is the author’s side of what this lesson read from the consumer’s side. For how a bundler or TypeScript resolves differently, see module resolution and module bundlers and build tools.

Check yourself

  1. 01`require('test')` fails with MODULE_NOT_FOUND but `require('node:test')` works. Why?

    `test` is not a built-in name in the bare form. `node:test` is a built-in that only exists with the prefix, so the prefix is required. A bare `test` is treated as an npm package name and searched for in `node_modules`, where nothing is found.

  2. 02Your project has `node_modules/dupe` at the top and `src/node_modules/dupe`. A file in `src` runs `require('dupe')`. Which one is loaded?

    The one in `src/node_modules`. Node walks up from the requiring file's directory and uses the first match, so the nearer copy shadows the outer one. That is also how a package can carry its own private version of a dependency.

  3. 03A package has both `"main": "./lib/entry.js"` and an `exports` field. Which does `require('pkg')` use?

    `exports`. When a package defines `exports`, Node ignores `main` for resolution on versions that support it. `main` remains only as a fallback for very old tools.

  4. 04How can you see which file `require('pkg')` would load without actually running it?

    Call `require.resolve('pkg')`, which returns the absolute path or throws if it cannot be found. `require.resolve.paths('pkg')` lists the directories Node will search, and `module.paths` shows them for the current file.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark