AceDevHub
Intermediate Node.js Interview QuestionsIntermediateConcept

Node.js · Question 36

How does module caching work in Node.js?

Direct answer

Node caches modules by resolved absolute path after first load — subsequent require/import of the same file return the same exports object; delete require.cache[path] forces reload (dev only); ESM cache is separate and not meant for hot reload via cache deletion.

Module caching implements the singleton pattern — config loaders, DB pool setup, and shared state run once per process. Understanding cache prevents surprise shared mutable state bugs.

Why interviewers ask

  1. First load — wrap module in function, execute, store exports in require.cache.
  2. Second load — return cached exports; module body does not re-run.
  3. Mutating exports — all importers see the same object if you mutate properties after load.
  4. Circular deps — partial exports visible because cache entry exists before module finishes (Q39).
module-cache.cjs
// counter.cjs
let count = 0;
module.exports = {
  increment() { return ++count; },
};

// app.cjs
const a = require("./counter.cjs");
const b = require("./counter.cjs");

console.log(a.increment()); // 1
console.log(b.increment()); // 2 — same instance

// Dev-only reload:
// delete require.cache[require.resolve("./counter.cjs")];