Module Caching (Node.js)

Node.js caches each module the first time it is required, so subsequent require() calls return the same exported object without re-running the file. This makes modules effectively singletons within a process.

Node.js

When you require('./config') in five files, Node runs config.js only once; the other four calls get the cached exports. This is why a module that exports a created object (a database connection, a config object) shares one instance across your whole app — a common and useful pattern.

The cache is keyed by the resolved absolute filename and lives in require.cache. Because of caching, module top-level code is initialization code that runs exactly once, which is the right place to set up singletons but the wrong place for per-call logic.

Caching occasionally surprises people in tests, where you may want a fresh module; you can delete an entry from require.cache to force a reload, though for testing it is usually cleaner to design modules as factory functions you call anew. ESM has analogous one-time evaluation semantics.

Syntax

require.cache   // map of loaded modules

Examples

JavaScript

// counter.js
let n = 0;
module.exports = () => ++n;

// a.js and b.js both: const inc = require('./counter');
// they share the same n because the module is cached

Learn it in a lesson

See also

Back to the Dictionary