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?
answer
- one execution per file
- cache keyed by resolved filename
- same module.exports object returned
- JSON files cached too
basics
~10 sNode 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 sThe 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
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.
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.
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.
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