In this post we will examine how the module initialization in Node.js is affected by the circular dependencies ( we will restrict this discussion to the CommonJS specification based module system)
I have created this simple system with three files, the main file app.js and other two modules modulea.js and moduleb.js
The two modules modulea and moduleb cross reference each other leading to a circular dependency.
I have put together few lines of code to check how the loading works as shown below.
The program produces the following output:
Let’s note the discrepancy, a.b.counter is 2 while b.a.counter is 1. This is due to the circular dependency and loading sequence of the modules as shown in the flow chart below.
b.a.counter value is 1 as the moduleb is loaded from the cache into app.js ( moduleb is already loaded while loading modulea and cached).
If we switch the sequence of initialization value will get altered as shown below:

