Skip to content
jshacks.dev
Node.js

How require() Resolves Modules

Follow the CommonJS resolution algorithm in Node.js step by step, from core modules and relative paths to node_modules lookups, package exports and caching.

6 min read
Summarize in AI
Flat illustration of a package parcel arriving from Composer, with the Node.js, Yarn, pnpm and GitHub logos.

When you write require("express") or require("./utils"), Node.js has to turn that string into a file on disk. The rules it follows are fixed, documented and surprisingly short, and knowing them removes a whole category of mysteries: why a module loads from an unexpected folder, why require("./data") finds a JSON file, why a package refuses deep imports, and why two requires of the same file return the same object. This post walks through the CommonJS algorithm on Node.js 24 in the order Node.js applies it, with a small project and the output of the checks you can run yourself.

For the module system that replaced it for new code, see how Node.js resolves ES module imports. The two differ in important ways, and the comparison is much easier once the CommonJS side is clear.

The steps in order

Given require(id), Node.js decides what to load by asking these questions in order.

  1. Is it a built-in module? If id names a core module, such as fs or node:fs, that module is returned at once, whatever is on disk. A node: prefix forces this check and skips everything else.

  2. **Does it start with ./, ../ or /?** Then it is a path. Node.js resolves it against the directory of the requiring file, and treats it as a file or a directory.

  3. Otherwise it is a package name. Node.js looks in a node_modules folder in the current directory, then in the parent's, and on up to the root, and finally in a few global folders.

Once a candidate path is found, the loader checks the cache. If the resolved file name has been loaded before, the cached exports are returned and nothing runs a second time.

A small project

The examples use this layout.

Text
project/
  resolve.cjs
  data.json
  lib/
    index.js
    util.js
  node_modules/
    shiny/
      package.json
      main.js
      internal.js

lib/index.js and lib/util.js hold ordinary modules. data.json contains {"ok": true}. The package shiny has a package.json with "main": "main.js", and the script below asks Node.js where each name leads.

resolve.cjsJavaScript
const path = require("node:path");
const { isBuiltin } = require("node:module");

function show(id) {
  const found = require.resolve(id);
  const shown = isBuiltin(id) ? found : path.relative(__dirname, found);
  console.log(`${id} -> ${shown}`);
}

show("./lib/util");
show("./lib");
show("./data");
show("shiny");
show("node:fs");
Text
./lib/util -> lib/util.js
./lib -> lib/index.js
./data -> data.json
shiny -> node_modules/shiny/main.js
node:fs -> node:fs

require.resolve runs the same algorithm as require and returns the path without loading the file. It is the best tool for answering "which file does this actually load?".

Files and directories

For a path, Node.js first tries it as a file. If ./lib/util is not an exact file name, it tries the name with each extension in order: .js, then .json, then .node for compiled addons. That is how ./data finds data.json when no data.js exists, and the order means a data.js would win over a data.json.

If the path names a directory, as ./lib does, Node.js reads the package.json in it, if any, and uses the main field. Without a main, it falls back to index.js, then index.json, then index.node. That is the origin of the common layout of a folder with an index.js that serves as its public face.

Package names and node_modules

A name with no leading dot, such as shiny, is searched in node_modules folders. If the requiring file is /home/me/project/src/app.js, the folders tried are:

Text
/home/me/project/src/node_modules
/home/me/project/node_modules
/home/me/node_modules
/node_modules

The first one that contains a match wins. You can see the list your file would use through module.paths. After those, Node.js tries the directories named in the NODE_PATH environment variable and a few legacy global folders under the home directory, which exist for historical reasons and are best avoided.

This walk up the tree has two consequences worth remembering. A package installed in a parent folder is visible to everything below it, which is how workspaces share dependencies. And two copies of a package at different depths are different modules, with separate state, a common source of the "instanceof returns false" class of bug.

The exports field takes over

When a package has an exports field in its package.json, Node.js uses it instead of the file layout. It defines the only entry points the package allows, and everything else is closed off.

node_modules/shiny/package.jsonJSON
{
  "name": "shiny",
  "main": "main.js",
  "exports": {
    ".": "./main.js"
  }
}

With that field in place, require("shiny") resolves to main.js, and any request for a path inside the package that is not listed fails, even though the file exists.

blocked.cjsJavaScript
try {
  require("shiny/internal");
} catch (err) {
  console.log(err.code);
}
Text
ERR_PACKAGE_PATH_NOT_EXPORTED

This encapsulation is the reason to prefer exports when you publish a package: you decide which files are public, and you can reorganise the rest without breaking anyone. It also explains an upgrade failure in which code that reached into some-package/lib/helper suddenly stops working. The package has added an exports field, and the deep import was never part of its public interface.

Conditions inside exports let a package pick different files for require and import, as the later posts on ES modules show. In CommonJS, the require and default conditions apply.

Caching

The first time a file is loaded, Node.js runs it, stores module.exports in require.cache under the file's resolved path and returns it. Every later require that resolves to the same path returns the stored object.

cache.cjsJavaScript
const first = require("./lib");
const second = require("./lib");

console.log(first === second);
console.log(Object.keys(require.cache).some((k) => k.endsWith("lib/index.js")));
Text
true
true

Because the key is the resolved path, two different strings that lead to the same file share one entry: require("./lib") and require("./lib/index.js") return one object. Because modules run once, top-level code with side effects, such as opening a connection, happens once per process. That is the reason a module can act as a singleton, and the reason tests that need a fresh copy sometimes delete the cache entry, which is a technique to use sparingly.

Symlinks are resolved to their real path before caching by default, so a package linked into two places is still one module. The --preserve-symlinks flag changes that, and it is rarely what you want.

Circular requires

If module a requires b while b is in the middle of requiring a, Node.js hands b the partially filled module.exports of a, not an error. This avoids an infinite loop and often gives the surprising undefined described in removing circular dependencies between modules.

Debugging resolution problems

When a require loads the wrong thing, ask the loader directly. require.resolve(id) shows the file. require.resolve.paths(id) lists the folders searched for a package name. module.paths shows the node_modules chain for the current file. Setting the environment variable NODE_DEBUG=module prints the loader's decisions to standard error, which is often enough to spot the wrong folder.

Check also for a stray package.json with the wrong main, a leftover index.js that shadows a folder you expected to resolve differently, and duplicate versions of a package in nested node_modules folders. Package managers' own commands, such as npm ls name, show duplicates.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.