← Back to Node.js, page 2

nodejs-0026 · Hard senior

How does Node.js find a package for require('name') or import 'name', and what does the exports field change?

For a bare name, Node looks in node_modules next to the importing file, then in each parent directory. Inside the package, the exports field (when present) lists the only allowed entry points and can pick different files for import and require. Paths not listed are blocked with ERR_PACKAGE_PATH_NOT_EXPORTED.

Full answer

For require('left-pad') or import 'left-pad', Node does not search your whole disk. It follows a fixed walk:

  1. Core modules first ('node:fs', and also 'fs').
  2. Relative or absolute paths ('./x', '/x') are loaded as files, or as directories with an index file or package.json main.
  3. Bare names are searched in node_modules next to the importing file, then in the parent directory's node_modules, up to the root. The first match wins. The list of folders is visible with require.resolve.paths('name').

Inside the found package, Node reads package.json:

  • Without exports, main decides the entry (default index.js), and any file inside the package can be required by path (require('pkg/lib/internal.js')).
  • With exports, only the listed paths are public. Anything else throws ERR_PACKAGE_PATH_NOT_EXPORTED. This lets a library hide its internal files and change them without a breaking release.
  • Conditions choose a file by how the package is loaded: "import" for ESM, "require" for CJS, "node", "default", and custom ones used by tools. The order matters, and "default" should be last.
  • Subpaths: "./feature": "./lib/feature.js". Patterns: "./utils/": "./lib/utils/.js".

Package managers shape this tree. npm hoists packages to reduce copies. pnpm uses links so a package can only reach its declared dependencies. Both rely on the same lookup rules.

javascript
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const { createRequire } = require('node:module');
const { pathToFileURL } = require('node:url');

const project = fs.mkdtempSync(path.join(os.tmpdir(), 'resolve-'));
const pkgDir = path.join(project, 'node_modules', 'greeter');
fs.mkdirSync(path.join(pkgDir, 'lib'), { recursive: true });

fs.writeFileSync(path.join(pkgDir, 'package.json'), JSON.stringify({
  name: 'greeter',
  exports: {
    '.': { import: './lib/index.mjs', require: './lib/index.cjs' },
    './feature': './lib/feature.js',
  },
}));
fs.writeFileSync(path.join(pkgDir, 'lib', 'index.cjs'), "module.exports = 'loaded the CommonJS build';");
fs.writeFileSync(path.join(pkgDir, 'lib', 'index.mjs'), "export default 'loaded the ESM build';");
fs.writeFileSync(path.join(pkgDir, 'lib', 'feature.js'), "module.exports = 'public feature';");
fs.writeFileSync(path.join(pkgDir, 'lib', 'secret.js'), "module.exports = 'private file';");

const requireFromProject = createRequire(path.join(project, 'index.js'));
console.log('require("greeter"):         ', requireFromProject('greeter'));
console.log('require("greeter/feature"): ', requireFromProject('greeter/feature'));

try {
  requireFromProject('greeter/lib/secret.js');
} catch (err) {
  console.log('require("greeter/lib/secret.js") failed with:', err.code);
}

console.log('first lookup folder is inside the project:',
  requireFromProject.resolve.paths('greeter')[0].startsWith(project));

// The same package loaded from an ES module picks the "import" condition.
fs.writeFileSync(path.join(project, 'main.mjs'), "import greeter from 'greeter'; export default greeter;");
import(pathToFileURL(path.join(project, 'main.mjs')).href).then((mod) => {
  console.log('import "greeter":           ', mod.default);
  fs.rmSync(project, { recursive: true });
});

The package is built in a temporary folder, so the snippet needs no install step. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, same on two runs): require("greeter"): loaded the CommonJS build require("greeter/feature"): public feature require("greeter/lib/secret.js") failed with: ERR_PACKAGE_PATH_NOT_EXPORTED first lookup folder is inside the project: true import "greeter": loaded the ESM build

Key points

  • Bare names are looked up in node_modules, walking up the directory tree.
  • exports defines the public entry points and blocks the rest.
  • Conditions such as import and require select different files.
  • require.resolve and require.resolve.paths show what Node will use.

Common mistakes

  • Reaching into package internals with deep imports and breaking when the author adds exports.
  • Putting default before the other conditions in the exports map.
  • Forgetting that main is ignored when exports is present in modern Node.
  • Assuming the first match in node_modules is always the newest version.

Follow-ups

  • What is the difference between require.resolve and require?
  • How does pnpm change the lookup?
  • Why can two copies of the same package appear in one project?

Tips

  • Say the search order out loud: core, relative, node_modules up the tree.
  • Explain exports as an encapsulation tool, not only a convenience.
  • Know the error code ERR_PACKAGE_PATH_NOT_EXPORTED.