Archive for August 15, 2021

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

image

The two modules modulea and moduleb cross reference each other leading to a circular dependency.

image

I have put together few lines of code to check how the loading works as shown below.

image

image

image

The program produces the following output:

image

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.

Untitled

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:

image

image