Circular dependencies in Node.js

What is cyclic/ circulardependencies in nodeJs

When required a module and we got {} instead.

Suppose, we have the following code

// moduleA.js
var ModuleB = require('./moduleB.js');
var ModuleA = function() {
  this.bInstance = ModuleB();
  this.property = 10;
}

var moduleA = new ModuleA();

module.exports = moduleA;
// moduleB.js
var moduleA = require('./moduleA.js');
var ModuleB = function() {}

ModuleB.prototype.doSomethingLater = function() {
  console.log(moduleA.property);
}

module.exports = ModuleB;
// main.js
var ModuleB = require('./moduleB.js');
var moduleB = new ModuleB();
moduleB.doSomethingLater();

When we run node main.js then we get the following error

  this.bInstance = ModuleB();
                   ^

TypeError: ModuleB is not a function

What is going on here – from main.js we are require moduleB. moduleB require moduleA then moduleB is exported to module via module.exports. Here node require work synchronously. So, when moduleB require moduleA before exporting it then it will get an empty object. But if we require moduleA after exporting moduleB then we will get the right object.

 

How to fix Circular Reference Issue

This is actually code smell. It is important to understand the effect of circular dependencies before fix it. There are so many way we can fix that.

But the most easiest/ quickest way to fix circular reference is to set the order. Just require the cyclic dependencies after the module.exports.

See the following example:

// moduleB.js
var ModuleB = function() {}

ModuleB.prototype.doSomethingLater = function() {
  console.log(moduleA.property);
}

module.exports = ModuleB;
var moduleA = require('./moduleA.js');

Now again we run node main.js then we will get our desire output.

 

You May Also Like

About the Author: Md. Delwar Hossain

He has 11 years of experience in developing standalone software and web applications for multiple database platforms. He has been passionate about new tools and technologies. He is positive and trustworthy. He is capable to learn and adapt quickly to different situations. He is a great team player and enjoys leading and mentoring. He is specialized in architecting and building complex web and mobile application. He has strong skills to automate POS, inventory, supply chain, trading export/ import, human resource management, manufacturing and production, distribution management system and hospital management system.

25 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *