skip to content

Module Formats and Loading

How Node finds, loads and caches code: CommonJS and ESM side by side, the resolution algorithm, loader hooks and running TypeScript. Asked because dual-format packages break in real migrations.

on this pageshow

explore

questions

19

In Node.js, three files require the same config module and one of them changes a property on it; why do the other two see the change?

level: juniorimportance: must knowfreq 62%

answer

  1. one execution per file
  2. cache keyed by resolved filename
  3. same module.exports object returned
  4. JSON files cached too

basics

~10 s

Node runs a CommonJS module once, caches it in require.cache under its resolved filename, and returns the same module.exports object to every later require of that file, so all callers share one mutable instance.

solid answer

~40 s

The first `require('./config')` resolves the specifier to an absolute filename, stores a new `Module` in `require.cache` under that key, runs the file once and returns `module.exports`. Every later `require` that resolves to the same file, whatever relative path it was written with, gets that identical object back without re-running the file. So the export is a process-wide singleton: set `cfg.timeoutMs` in one file and every holder sees it. JSON loaded with `require` is cached the same way, so a required `settings.json` is one shared, mutable object. When callers need separate state, export a factory function and call it instead of relying on top-level state.

go deeper

for a junior

Recall that require runs a file once and then returns the same exports object to every caller, which is why changes are shared across files.

for a middle

Explain that require.cache is keyed by resolved filename and populated before the file runs, and that required JSON is cached and shared just like code.

for a senior

Show you know when the singleton splits: duplicate package copies, casing on case-insensitive file systems, cache deletion, and a module that throws being re-run on the next require.

for a principal

Weigh module-level state against explicit factories or injected instances, since hidden process-wide singletons couple every caller and make tests and multi-tenant code harder to reason about.

## What `require` does the first time When a CommonJS file calls `require('./config')`, Node's CommonJS loader works through a short, fixed sequence: 1. **Resolve** the specifier to an absolute filename such as `/srv/app/config.js` (how that lookup works is a separate subject). 2. **Check `require.cache`**, an object keyed by resolved filename. On a miss, Node creates a new `Module` object and stores it in the cache *before* running any of the file's code. 3. **Execute** the file once, inside its module wrapper, letting it fill in `module.exports`. 4. **Return** `module.exports` to the caller. Step 2 happening before step 3 matters: it is what lets a file that is still running be handed out to a circular `require`, and it is what makes every later call cheap. ## Every later `require`: a cache hit The second, third and hundredth call that resolves to the same file finds the entry in `require.cache` and returns the **same `module.exports` object**. The file's top-level code does not run again. The Node documentation states it directly: every call to `require('foo')` gets exactly the same object returned, if it would resolve to the same file. The key is the **resolved filename**, not the string you typed. So these all share one instance when they point at the same file: - `require('./config')` from `src/server.js` - `require('../config.js')` from `src/routes/users.js` - `require('/srv/app/config')` from anywhere ## Why this makes a process-wide singleton Because every caller holds a reference to one object, the module behaves as a **singleton for the lifetime of the process**: - A property one file sets, such as `cfg.timeoutMs = 500`, is visible to every other holder immediately. - A `Map`, connection pool or counter created at the module's top level is created once and shared. - **JSON files** loaded with `require('./settings.json')` go through the same cache. Node parses the file once and every caller receives the same mutable object, so one file writing `settings.port = 9000` changes it for everyone. - Nothing about this is a copy: callers that destructure (`const { timeoutMs } = require('./config')`) capture the value at that moment, while callers that keep the object see later changes. This is useful for configuration that should be read once and for shared resources such as a pool, and dangerous when one caller treats a shared object as its own scratch space. ## When the cache does not give you one instance The guarantee is "same resolved filename, same object". Several situations produce two filenames, and therefore two executions and two independent objects: | Situation | Why there are two instances | |---|---| | Two copies of a package in different `node_modules` folders | Each copy resolves to its own path, so each is cached and run separately | | `require('./foo')` and `require('./FOO')` on a case-insensitive file system | The cache key differs even though the file is the same, as the docs warn | | One file reached through two symlinked paths under `--preserve-symlinks` | The flag keeps link paths as the identity, so each path is its own entry | | Someone deletes the entry from `require.cache` | The next `require` executes the file again and returns a new object | By default Node resolves symlinks to the real on-disk path and uses that as the identity, which is why a symlinked module normally still shares one instance. ## Failures are not cached If the module's top-level code throws during its first load, Node removes its entry from `require.cache` before the error reaches the caller. A later `require` of the same file runs it again from the top. A module that half-initialised a shared resource before throwing can therefore initialise it twice. ## Getting a fresh copy on purpose When each caller genuinely needs its own state, do not fight the cache. **Export a function** and call it, which is exactly what the Node docs recommend for running module code more than once: - `module.exports = function createRateLimiter(opts) { ... }` gives each caller a new limiter. - Keep truly shared, read-only data (parsed configuration, constants) at the top level, and freeze it with `Object.freeze` if accidental mutation is a risk. The rule of thumb: top-level module code runs once per resolved file per process, and everything it creates is shared by every file that requires it.

  • In Node.js, can the same package still end up loaded twice in one process?
    Yes. The cache is keyed by resolved filename, so two copies of a package installed in different `node_modules` folders are two files, two executions and two objects. Different letter casing for the same file on a case-insensitive file system, or running with `--preserve-symlinks`, can also produce two keys. Anything that relies on one instance, such as a registry or `instanceof` checks, then silently splits.
  • In Node.js, if a CommonJS module throws during its first load, what does the next require of it do?
    It runs the file again. Node deletes the module's `require.cache` entry when loading throws, so a caller that catches the error and requires again gets a fresh execution, not a cached failure. Any side effect the first attempt performed before throwing, such as opening a handle, can happen twice.

A shared document link: everyone who opens it gets the same live document rather than a downloaded copy, so one person's edit is what everyone else reads next.

  • Each file that calls require gets its own fresh copy of the module
  • Requiring a JSON file returns a new parsed object on every call
  • The cache key is the specifier string written in the require call
  • Destructured values from require update when the module later changes them
open as a page

In Node.js 24, how does Node decide whether a given .js file runs as an ES module or as CommonJS?

level: juniorimportance: must knowfreq 64%

basics

~20 s

An .mjs file is always an ES module and a .cjs file always CommonJS. A .js file follows the nearest package.json "type" field; without one, Node 24 tries CommonJS and reparses as ESM if it finds module syntax.

open as a page

In Node.js, how does `require()` turn a bare specifier such as `'some-package'` into a file on disk, and where does it look?

level: juniorimportance: must knowfreq 58%

basics

~20 s

Built-in names win first. Otherwise Node checks the node_modules folder beside the calling file, then each parent's, up to the filesystem root, then NODE_PATH and global folders. In the package found, exports beats main; without exports, extensions and index files are probed.

open as a page

Moving a Node.js 24 file from CommonJS to ESM, which CommonJS module-scope bindings disappear, and what does Node offer in place of each?

level: middleimportance: must knowfreq 58%

basics

~10 s

In an ES module, require, module, exports, __filename and __dirname do not exist. Node 24 replaces them with import and export, import.meta.filename and import.meta.dirname, import.meta.resolve(), and module.createRequire(import.meta.url) when a real require is still needed.

open as a page

In Node.js, why does `import './utils'` fail in an ES module when `require('./utils')` finds `utils.js` from CommonJS?

level: middleimportance: must knowfreq 55%

basics

~10 s

Node's ES module resolver resolves relative specifiers as URLs and never adds extensions or looks for index files, so './utils' must be written './utils.js'. A missing file throws ERR_MODULE_NOT_FOUND; a folder throws ERR_UNSUPPORTED_DIR_IMPORT.

open as a page

In Node.js 24, what happens when you run `node server.ts`, and what does Node deliberately not do with the TypeScript?

level: juniorimportance: should knowfreq 45%

basics

~20 s

Node.js 24 runs the file directly: built-in type stripping replaces erasable TypeScript syntax with whitespace and runs the JavaScript that remains. It does not type-check, does not read tsconfig.json and does not generate code for syntax like enum.

open as a page

In Node.js CommonJS, what is the module wrapper function, and how does it give each file its own exports, require, module, __filename and __dirname?

level: middleimportance: should knowfreq 50%

basics

~20 s

Node wraps each CommonJS file's source in a function taking exports, require, module, __filename and __dirname, then calls it once with this set to module.exports, so those names are per-file arguments and top-level variables stay module-local.

open as a page

When a Node.js 24 ES module imports a CommonJS file, what does the resulting namespace contain, and when are its named exports fixed?

level: middleimportance: should knowfreq 42%

basics

~20 s

Node builds a namespace whose default export is the CommonJS module.exports value, plus a 'module.exports' key with the same value. Extra named exports come from static analysis of the source and are copied once at import, never updated live.

open as a page

In Node.js 24, why do stack traces from compiled TypeScript point at the `.js` output, and what does `--enable-source-maps` change?

level: middleimportance: should knowfreq 30%

basics

~20 s

V8 reports positions in the JavaScript it actually ran, and Node ignores sourceMappingURL comments by default. --enable-source-maps makes Node load those maps and rewrite stack frames to original .ts lines, at a cost each time Error.stack is read.

open as a page

In Node.js, why does `require('my-package/lib/helpers')` throw `ERR_PACKAGE_PATH_NOT_EXPORTED` after the package adds an `exports` map in a minor release?

level: middleimportance: should knowfreq 45%

basics

~10 s

Once a package defines exports, Node resolves only the subpaths that map lists, with no extension or index probing. './lib/helpers' is not a key, so resolution throws ERR_PACKAGE_PATH_NOT_EXPORTED even though the file still exists.

open as a page

In a Node.js application, what does the package.json `imports` field do, and how does `import '#internal/db.js'` get resolved?

level: middleimportance: should knowfreq 25%

basics

~20 s

The imports field defines private, '#'-prefixed specifiers for code inside one package. Node finds the importing file's nearest package.json, matches '#internal/db.js' against its imports keys and patterns, and resolves the target from the package root, for both import and require().

open as a page

A Node.js service logs "Accessing non-existent property 'query' of module exports inside circular dependency" and later fails with query is not a function; what is happening, and how do you fix it?

level: seniorimportance: should knowfreq 35%

basics

~20 s

Two CommonJS files require each other, so one received the other's unfinished module.exports and read query before it existed. Break the cycle, or keep the object and read the property at call time without replacing module.exports.

open as a page

In a Node.js test run where test files share one process, a required cache module leaks entries between files; how do you isolate it, and what does deleting its require.cache entry not reset?

level: seniorimportance: should knowfreq 38%

basics

~20 s

Move the state out of module scope with a factory, reset function or injected instance, or run files in separate processes. Deleting require.cache[require.resolve(path)] only makes the next require re-run the file; existing holders keep the old object.

open as a page

In a CommonJS Node.js 24 service, what does require() return for an ESM-only dependency, and when does it throw ERR_REQUIRE_ASYNC_MODULE instead?

level: seniorimportance: should knowfreq 46%

basics

~20 s

Node 24's require() loads a synchronous ES module and returns its module namespace object, with any default export under .default. If the module or anything it imports uses top-level await, require() throws ERR_REQUIRE_ASYNC_MODULE and import() must be used instead.

open as a page

A Node.js 24 service runs on built-in type stripping; which TypeScript constructs does it refuse at run time, and how do you fix each one?

level: seniorimportance: should knowfreq 35%

basics

~20 s

Node.js 24 type stripping refuses syntax that needs generated JavaScript (enum, parameter properties, namespaces with runtime code, import aliases), decorators, tsconfig paths aliases, .tsx and TypeScript under node_modules. Rewrite to erasable syntax, or build ahead.

open as a page

In Node.js conditional exports, how does the resolver choose between `import`, `require`, `node` and `default`, and why does key order in the object matter?

level: seniorimportance: should knowfreq 35%

basics

~20 s

Node walks the condition object's keys in their written order and takes the first whose name is active or is default. import is active for import and import(), require for require(), node always; so a default key written first wins for everyone.

open as a page

You lead a large CommonJS Node.js 24 service that now depends on one ESM-only and one CommonJS-only package; how do you decide whether, and how, to move it to ESM?

level: principalimportance: should knowfreq 30%

basics

~20 s

In Node 24, require() loads synchronous ES modules, so an ESM-only dependency without top-level await no longer forces a migration. Decide on cost: tests, mocks and require-patching tools, against what ESM buys, such as top-level await.

open as a page

Your team runs several TypeScript services on Node.js 24: would you ship them through built-in type stripping, a runner such as tsx, or a compiled build, and why?

level: principalimportance: should knowfreq 30%

basics

~20 s

No single answer: built-in type stripping suits services written in erasable syntax, a compiled build suits code needing decorators, enums or tsconfig features and libraries, and a full-syntax runner mainly fits development. Every option still needs a separate type-check step.

open as a page

In Node.js 24, how do `module.registerHooks()` resolve and load hooks customise module loading, and how do you make them cover the whole application?

level: seniorimportance: nice to knowfreq 20%

basics

~20 s

module.registerHooks() installs synchronous, in-thread hooks: resolve maps a specifier to a URL and load returns that URL's format and source. Each must call the next hook or return shortCircuit: true. Preload the registering file with --import so hooks precede the entry point.

open as a page