How a module is found: node_modules, main and exports

require takes a name and returns a value, and between those two points sits a lookup that reads the file system. A relative name starts with a dot and names a file or a folder of the project; a bare name is a package, and node searches node_modules from the folder of the calling file upward to the root of the disk.

The lesson builds a folder with the same package installed twice at different depths, requires it from both places, then adds a manifest with a main field and one with an exports map, which is the newer and stricter way to say which files a package shows. The last program reads the error of a name that no folder has.

The nearest node_modules

The fixture is small on purpose: a package called box at the root of the project, a second copy of it inside src/deep, and a program at each level. Nothing is installed, because the lookup only cares about folders.

resolve-course/ package.json exports.js lib/ package.json entry.js message.js src/ main.js deep/ which.js node_modules/box/lib/box.js node_modules/box/ package.json lib/box.js lib/feature.js src/secret.js

The program in the deep folder requires box and prints the name the module exports, the file that answered, and the first three folders of the search. The copy in src/deep/node_modules is nearer than the one at the root, so it wins.

The file src/deep/which.js:

const path = require('node:path'); const box = require('box'); console.log('the box here says:', box.name); console.log('the box file is:', path.relative(process.cwd(), require.resolve('box'))); const dirs = require.resolve.paths('box'); console.log('the first three folders of the lookup:'); for (const dir of dirs.slice(0, 3)) { console.log(' ' + path.relative(process.cwd(), dir)); }

node src/deep/which.js

the box here says: the box of the deep folder
the box file is: src/deep/node_modules/box/lib/box.js
the first three folders of the lookup:
  src/deep/node_modules
  src/node_modules
  node_modules

The search started in the folder of the file that called require and not in the folder the command was run from, which is the rule that makes a monorepo work. It went up one level at a time and stopped at the first folder that had the package, so the second copy was never reached. A project that accidentally has two copies of a package gets the nearer one, and the two copies are two different modules with two different sets of state.

main and the entry of a folder

A relative name without an extension is tried as a file first and as a folder second. As a folder, node reads its package.json and uses the main field; without that field it tries index.js. The folder lib of the fixture names its entry entry.js, and the program at the root requires both the package by name and the folder by path.

The file lib/package.json:

{ "name": "lib", "version": "1.0.0", "main": "entry.js" }

The file src/main.js:

const path = require('node:path'); const box = require('box'); const lib = require('../lib'); console.log('the box module says:', box.name); console.log('the box file is:', path.relative(process.cwd(), require.resolve('box'))); console.log('the lib package says:', lib.hello()); console.log('the lib entry is:', path.relative(process.cwd(), require.resolve('../lib')));

node src/main.js

the box module says: the box of the project
the box file is: node_modules/box/lib/box.js
the lib package says: hello from lib/entry.js
the lib entry is: lib/entry.js

The same main rule answered for the package and for the relative folder, because the resolver does not care whether the folder sits in node_modules or beside the caller. lib/entry.js requires ./message without an extension, and the file message.js is the first candidate that exists.

The exports map

exports is the modern replacement for main, and it is a whitelist: once a package has the field, only the subpaths it names can be required, and main is ignored. The package box exports its root and one named subpath, and keeps a third file out of reach.

The file node_modules/box/package.json:

{ "name": "box", "version": "1.0.0", "main": "lib/box.js", "exports": { ".": "./lib/box.js", "./feature": "./lib/feature.js" } }

The file exports.js:

const path = require('node:path'); console.log('the feature entry:', path.relative(process.cwd(), require.resolve('box/feature'))); try { require('box/src/secret'); } catch (error) { console.log('the code:', error.code); console.log('the message:', error.message.replace(process.cwd(), '.')); }

node exports.js

the feature entry: node_modules/box/lib/feature.js
the code: ERR_PACKAGE_PATH_NOT_EXPORTED
the message: Package subpath './src/secret' is not defined by "exports" in ./node_modules/box/package.json

The error is deliberate and it is the point of the field: the file exists and the resolver refuses it, because a name that is not in the map is not part of the package. The message names the subpath, the field and the manifest, and the code is the one a handler should test rather than the text. A package that adds exports therefore removes access to every file it does not list, which is a breaking change for the callers that reached inside.

A name that is not there

When no folder has the package, the lookup ends with one error, and its message carries the answer for the reader: the name and, on the following lines, the folders that were tried. The program keeps the code and the first line.

The file not-found.js:

try { require('nothing'); } catch (error) { console.log('the code:', error.code); console.log('the message:', error.message.split('\n')[0]); }

node not-found.js

the code: MODULE_NOT_FOUND
the message: Cannot find module 'nothing'

MODULE_NOT_FOUND is also the code of a relative name that points at a file which does not exist, and the message starts with Cannot find module in both cases. The next lesson adds a linter, whose first useful error is the same kind of name that the resolver cannot see.

Exercises

  1. Delete src/deep/node_modules and run the program there again. Which copy answers now, and what does the list of folders say?
  2. Rename lib/entry.js to index.js and remove the main field. Does require('../lib') still work?
  3. Add a third subpath to the exports map and require it. Which two strings have to agree, and what happens when they do not?
  4. Require a package by a name that is in node_modules but not in the manifest. Which command reports the situation, and what does the resolver do?
  5. Print require.resolve.paths('box').length from the root and from the deep folder. Which folder accounts for the difference?

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. Where does the lookup of a bare name start?

    Answer

    In the folder of the file that called require

    The search walks up from the calling file, which is why a nested node_modules wins.

  2. What does this program print? const path = require("node:path"); console.log(path.relative("/app/src/deep", "/app/node_modules/box/lib/box.js"));

    Answer

    ../../node_modules/box/lib/box.js

    Two levels up from src/deep reach the root of the project, and the rest of the path follows.

  3. Which file does node load for a folder with no main field and no exports?

    Answer

    index.js

    index.js is the fallback of the folder rule, and there is no scan of the directory.

  4. What does this program print? const lookups = ["/app/src/deep/node_modules", "/app/src/node_modules", "/app/node_modules"]; console.log(lookups.findIndex((dir) => dir.endsWith("node_modules") && dir.includes("/app/src/")));

    Answer

    0

    The first entry is the nearest one and it satisfies both conditions.

  5. What does the exports field do once a package has one?

    Answer

    It closes every subpath that it does not list

    The map is a whitelist, and the error for a missing subpath is ERR_PACKAGE_PATH_NOT_EXPORTED.

  6. What does this program print? const pkg = { main: "lib/box.js", exports: { ".": "./lib/box.js", "./feature": "./lib/feature.js" } }; console.log(Object.keys(pkg.exports).join(","), pkg.exports["."]);

    Answer

    .,./feature ./lib/box.js

    The keys keep the order of the object and the dot maps to the path with the leading dot-slash.

  7. What is the code of the error for a package that no folder has?

    Answer

    MODULE_NOT_FOUND

    The resolver reports a missing name with MODULE_NOT_FOUND, and a closed subpath with its own code.

  8. What does this program print? const dirs = ["src/deep/node_modules", "src/node_modules", "node_modules"]; console.log(dirs.slice(0, 2).join(" | "));

    Answer

    src/deep/node_modules | src/node_modules

    slice with a stop of two keeps the first two entries and drops the third.

  9. Two files require the same package name and two different copies exist. What happens?

    Answer

    Each file gets the nearest copy, so the two modules are different objects

    The cache is keyed by the resolved file, and two files mean two entries with separate state.

  10. What does this program print? const paths = ["a/node_modules", "node_modules"]; console.log(paths.indexOf("node_modules"));

    Answer

    1

    The exact string is the second entry, and indexOf counts from zero.

The programs on this page were run with Node.js 24.22.1 and linted with ESLint 10.14.0 on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev

Banner image