Skip to content

How require and import find a module

Working knowledgeUnder the hood

You write require('express') or import { x } from './db.js' and Node finds a file. Here are the rules it follows, drawn one folder at a time, and why the same name can load different files from require and import.

01 Three kinds of name

The string you pass is a specifier. Its first characters decide where Node looks.

How Node reads a specifier
KindExampleWhere Node looks
Relative./db.jsNext to the file that asks, following the path
Absolute/srv/app/db.jsExactly that path
Built-innode:fsInside Node itself; never on disk
Baretiny-cachenode_modules folders, then the package’s package.json

Built-ins can also be written without the node: prefix (fs), and they win over a package with the same name. The prefix makes the intent obvious, so prefer it.

02 Relative paths and file extensions

CommonJS (require) is forgiving. For require('./db') it tries the exact path, then db.js, db.json and db.node. If db is a folder, it reads db/package.json for a main field, then tries db/index.js.

ES modules (import) do none of that. A relative import must name the file exactly, extension included, just as a browser would need the full URL.

ES module, no extension
import db from './db';
// Error [ERR_MODULE_NOT_FOUND]:
// Cannot find module '/app/src/db'
ES module, full name
import db from './db.js';
// loads /app/src/db.js

03 Bare names: walk up to node_modules

For a bare name, Node starts at the folder of the file that asked and looks for node_modules/<name>. If it is not there, it moves up one folder and tries again, all the way to the root. The first match wins.

Finding a bare name: walking up to node_modules
Step 1 of 6
Folders whose node_modules is checked, nearest first
routes/
src/
app/
ana/
home/
/
Resolver’s notes
Empty
  • checking now
  • checked, not there
  • package found
  • never needed
  • just noted

/home/ana/app/src/routes/users.js runs require('tiny-cache'). The name has no ./ and is not built in, so it is a bare name: Node will search node_modules folders. Nothing is checked yet.

tiny-cache asked for

This walk is why a package installed in a project’s root node_modules is visible to every file under it, and why a copy nested deeper, in node_modules/some-lib/node_modules/, takes priority for files inside some-lib.

04 package.json exports: the package decides

Once the package folder is found, its package.json decides which file you get. The modern way is an exports map. Each key is a subpath a user may ask for; each value can branch on conditions such as import, require and default.

node_modules/tiny-cache/package.json
{
"name": "tiny-cache",
"version": "1.0.0",
"exports": {
".": {
"import": "./esm/index.js",
"require": "./cjs/index.cjs"
},
"./lru": {
"import": "./esm/lru.js",
"require": "./cjs/lru.cjs"
}
}
}
Matching a request against package.json exports
Step 1 of 3
Called by import
tiny-cache/package.json · exports
"." · import→./esm/index.js"." · require→./cjs/index.cjs"./lru" · import→./esm/lru.js"./lru" · require→./cjs/lru.cjs
  • subpath matches
  • condition matches

An ES module runs import { lru } from 'tiny-cache/lru'. Node has found the package folder as before, and now consults its exports map. Nothing is matched yet.

tiny-cache/lru asked for

A require('tiny-cache/lru') from CommonJS would match the same subpath but take ./cjs/lru.cjs. One more rule: once a package has exports, any path not listed is closed. require('tiny-cache/cjs/index.cjs') fails with ERR_PACKAGE_PATH_NOT_EXPORTED, even though the file is on disk. Without exports, Node falls back to main, and then to index.js.

05 CommonJS or ES module?

Node decides how to treat each file before it runs it:

  • .cjs is always CommonJS, and .mjs is always an ES module.
  • .js follows the nearest package.json above it: "type": "module" means ES module; "type": "commonjs" or no type means CommonJS.
  • Recent Node versions (22.7 and later) also spot ES module syntax in a .js file with no type and run it as an ES module, with a warning telling you to add "type".
What changes between the two
AspectCommonJSES modules
Syntaxrequire() and module.exportsimport and export
When it loadsSynchronously, when the require line runsAll imports found and linked before any code runs
Relative extensionsOptionalRequired
Current folder__dirnameimport.meta.dirname (Node 20.11+)
Top-level awaitNoYes
Loading the other kindrequire() of an ES module works in Node 20.19+ and 22.12+, unless it uses top-level awaitimport of CommonJS works; module.exports becomes the default export

06 Loaded once, then cached

Each module runs once per process. The cache is keyed by the resolved full path, so two specifiers that land on the same file share one instance, and that is how a module-level database pool or config object becomes a singleton.

Two copies of a package in different node_modules folders are two different paths, so they load twice: two singletons, and instanceof checks that fail across them. The same happens when one part of an app imports the ES build of a package and another requires its CommonJS build. Run npm ls <name> to see how many copies you have.

07 See it yourself

Node will tell you where it would look and what it would load, without loading anything else:

Shell
$ cd /home/ana/app
$ node -p "module.paths.slice(0, 3)"
[
'/home/ana/app/node_modules',
'/home/ana/node_modules',
'/home/node_modules'
]
$ node -p "require.resolve('tiny-cache')"
/home/ana/app/node_modules/tiny-cache/cjs/index.cjs
$ node --input-type=module -e "console.log(import.meta.resolve('tiny-cache'))"
file:///home/ana/app/node_modules/tiny-cache/esm/index.js

Note that require.resolve and import.meta.resolve pick different files for the same name, because they bring different conditions to the exports map.

08 When it goes wrong

import { x } from './utils'No extension in an ES moduleERR_MODULE_NOT_FOUND. Write ./utils.js, even in TypeScript source that compiles to .js.
require('pkg/lib/helper.js')A path the package did not exportERR_PACKAGE_PATH_NOT_EXPORTED. Use a listed subpath; reaching into a package’s internals is exactly what exports stops.
"type": "module"Switching a project to ES modulesEvery .js file is now an ES module, so old files fail with require is not defined in ES module scope. Rename them to .cjs or convert them.
console.log(__dirname)CommonJS globals in an ES module__dirname, __filename and require do not exist there. Use import.meta.dirname, import.meta.filename and import.
import User from './user.JS'Wrong letter casemacOS and Windows file systems are case-insensitive by default; Linux is not. It works on your laptop and fails in CI or production.

09 Check yourself

Question

/home/ana/app/src/users.js runs require('tiny-cache'). Copies exist in /home/ana/app/node_modules and /home/ana/node_modules. Which loads?

Question

An ES module runs import { x } from './utils', and utils.js sits next to it. What happens?

Question

A package’s exports lists only ".". You require('pkg/lib/helper.js'), and that file exists on disk. What happens?

10 Practise this

Was this tutorial useful?Your vote tells us what to improve next.
Spotted a mistake, or something unclear?