Module scope and caching
CommonJS modules have file-local scope and are normally cached after loading. Requiring the same resolved file again in one process generally returns the same exported object rather than re-running the module’s initialization code.
Local practice: The proposed teaching runtime is Node.js 26.13.1 LTS. These original offline examples were executed on Node.js 22.16.0 (Linux x64); execution on the proposed baseline and in ByteMind is not yet verified. No npm dependencies are required. Use a fresh practice directory. Code blocks are static, not a browser-based Node runner.
Observe shared module state
const first = require("./counter.cjs");const second = require("./counter.cjs");console.log(first.next());console.log(second.next());console.log(first === second);In the directory containing the files above, run:
node main.cjsExpected standard output:
12trueExpected exit status: 0.
How it works
Node wraps CommonJS module source so top-level declarations are local to that module. In the counter fixture, the exported functions close over a private variable. Two require calls resolving to the same file share the cached export object, so incrementing through either reference updates the same counter. Caching is based on resolution; different filenames, separate processes or unusual resolution configurations can change identity. In the factory example, the module exports a function that creates fresh state per call, even though the factory module itself is cached.
Create independent counters with a factory
module.exports = function makeCounter() { let value = 0; return () => ++value;};const makeCounter = require("./factory.cjs");const first = makeCounter();const second = makeCounter();console.log(first());console.log(first());console.log(second());In the directory containing the files above, run:
node main.cjsExpected standard output:
121Expected exit status: 0.
Common mistake
Cached module state is not a durable database or a universal singleton across processes and workers. Unintended shared mutable state can couple unrelated requests and tests. Prefer explicit instances or factories when callers need independent state. Do not routinely clear require.cache to manage application state.
Try it yourself
Extend the factory example with a third counter. Predict the sequence before running it. Explain why the factory creates independent state even though require returns a cached module.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Module scope and caching — knowledge check
Check your understanding of module scope and caching.
Why does the second next() call print 2 in the first fixture?
Does CommonJS caching make state shared across separate Node processes?
How does a factory help?