How to deal with cyclic dependencies in Node.js


I've been working with nodejs lately and still getting to grips with the module system so apologies if this is an obvious question. I want code roughly like the following below:

a.js (the main file run with node)

var ClassB = require("./b");

var ClassA = function() {
    this.thing = new ClassB(); = 5;

var a = new ClassA();

module.exports = a;


var a = require("./a");

var ClassB = function() {

ClassB.prototype.doSomethingLater() {

module.exports = ClassB;

My problem seems to be that I can't access the instance of ClassA from within an instance of ClassB.

Is there a correct / better way to structure modules to achieve what I want? Is there a better way to share variables between modules?

12/28/2014 10:36:53 PM

Accepted Answer

While node.js does allow circular require dependencies, as you've found it can be pretty messy and you're probably better off restructuring your code to not need it. Maybe create a third class that uses the other two to accomplish what you need.

5/22/2014 1:16:45 AM

Try to set properties on module.exports, instead of replacing it completely. E.g., module.exports.instance = new ClassA() in a.js, module.exports.ClassB = ClassB in b.js. When you make circular module dependencies, the requiring module will get a reference to an incomplete module.exports from the required module, which you can add other properties latter on, but when you set the entire module.exports, you actually create a new object which the requiring module has no way to access.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow