What happens when you require the same module twice in Node.js?
The file runs only once. Node caches the exported object in require.cache, so later require calls return the same object, which means shared state between files.
Explain it simply
Think of a college library with one copy of a reference book. The first student who asks for it makes the librarian fetch it from the shelf. Every later student gets the very same copy from the desk. Node treats modules the same way: the first require finds the file, runs it, and stores the result under its resolved filename. Every later require of that file gets the stored result without running the code again.
Example
// counter.js
console.log("counter.js is running");
let count = 0;
module.exports = { next: () => ++count };
// app.js
const a = require("./counter"); // prints: counter.js is running
const b = require("./counter"); // prints nothing, cache hit
console.log(a === b); // prints: true
console.log(a.next(), b.next()); // prints: 1 2Because both variables are the same object, state inside the module is shared. This is why a database connection created in one module can be reused everywhere by simply requiring it, a pattern often called a singleton.
You can delete an entry with delete require.cache[require.resolve("./counter")], but that is rarely a good idea outside tooling.
What to say in the interview
"A module executes once; the exports object is cached by resolved path in require.cache. Every require returns that same object, so module-level state is shared across the app."
Common mistakes
- Expecting top-level code in a module to run on every require.
- Exporting mutable state and being surprised when two files see each other's changes.