Advanced Node.js Interview QuestionsAdvancedCode Output
Node.js · Question 87
What is the output of this require cache example?
Direct answer
Output: module run, 1, 2, true — the module body runs once; both requires share the same exports object; increment mutates shared state (Q36).
This tests require.cache singleton behavior — a frequent follow-up to module caching and exports questions.
require-cache
// counter.cjs
console.log("module run");
let count = 0;
module.exports = {
inc() { return ++count; },
};
// main.cjs
const a = require("./counter.cjs");
const b = require("./counter.cjs");
console.log(a.inc());
console.log(b.inc());
console.log(a === b);Output
module run 1 2 true
- module run once — second require hits cache; body does not re-execute.
- 1 then 2 — shared count variable across both references.
- true — a and b reference identical exports object.