CodePark/ questions / Modules (CommonJS & ESM)
START PRACTICINGPRACTICE
Backend question · Node.js › Modules (CommonJS & ESM)

What does main.js log?

// counter.js
let n = 0;
module.exports = { inc: () => ++n };

// main.js
const a = require("./counter");
const b = require("./counter");
a.inc();
console.log(b.inc(), a === b);
2 true

Node caches a module after the first require. The cache key is the module's resolved filename. The second require returns the same module.exports object and does not run the file again. So both variables share one counter. This is why modules work as singletons (only one instance exists). It is also why deleting the entry from require.cache is the only way to force a reload.