Circular dependencies in CommonJS modules
deep understanding of CommonJS loading.
when A requires B which requires A, the cache returns A's partial exports; fields defined later are undefined at that moment.
WHAT THIS TESTS This probes whether you truly understand the mechanics of CommonJS loading and caching, since circular dependencies fail silently and subtly rather than loudly.
A GOOD ANSWER COVERS A circular dependency exists when module A requires module B and B, directly or through a chain, requires A. CommonJS handles this without throwing by relying on its module cache. When a module starts loading, Node immediately places its exports object, initially empty, into the cache. If during A's execution it requires B, and B then requires A, Node sees A already in the cache and returns A's current exports rather than re-running A. The catch is that A may not have finished assigning its exports yet, so B receives a partially populated object. Any property A defines after the point where it required B will be undefined from B's perspective at that moment.
COMMON WRONG ANSWERS Claiming Node throws an error or deadlocks on cycles, asserting exports are always fully populated, or believing ESM behaves identically, when ESM uses hoisted live bindings that handle some cycles more gracefully but can still throw temporal dead zone errors.
LIKELY FOLLOW-UPS How to break a cycle by moving shared logic to a third module, why ordering the require statement after assignments can help, how lazy require inside functions defers resolution, and how ESM live bindings differ.
ONE CONCRETE EXAMPLE Suppose a.js sets module.exports.first then requires b.js, then sets module.exports.second. Inside b.js it requires a.js and reads both properties at load time. Because a.js had only assigned first before requiring b.js, b.js sees first defined but second undefined, even though a.js later completes. If b.js instead reads second lazily inside a function called after both modules finish loading, it sees the complete object, which is the common workaround.
Read the original → nodejs.org
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.