229

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 below:

a.js (the main file run with node)

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

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

var a = new ClassA();

module.exports = a;

b.js

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

var ClassB = function() {
}

ClassB.prototype.doSomethingLater() {
    util.log(a.property);
}

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 any correct / better way to structure modules to achieve what I want? Is there a better way to share variables across modules?

2
  • I suggest you look in to command query separation, observable pattern and then what the CS guys call managers - which is basically a wrapper for the observable pattern.
    – dewwwald
    Oct 16, 2017 at 19:00

16 Answers 16

204

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, to which you can later add other properties, but when you set the entire module.exports, you actually create a new object which the requiring module has no way to access.

3
  • 8
    This might be all true, but I would say still avoid circular dependencies. Making special arrangements to deal with modules that have incompletely loaded sounds like it will create a future problem you don't want to have. This answer prescribes a solution to how to deal with incompletely loaded modules...I don't think that's a good idea. Jun 1, 2015 at 19:05
  • 1
    How would you put a class constructor in module.exports without fully replacing it, to allow other classes to 'construct' an instance of the class?
    – Tim Visée
    Aug 7, 2016 at 12:21
  • 1
    I don't think you can. Modules that have imported your module already will not be able to see that change
    – lanzz
    Aug 7, 2016 at 14:37
127

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.

10
  • 8
    +1 This is the right answer. Circular dependencies are code smell. If A and B are always used together they are effectively a single module, so merge them. Or find a way of breaking the dependency; maybe its a composite pattern.
    – James
    Sep 30, 2014 at 11:39
  • 131
    Not always. in database models, for example, if I have model A and B, in model A I may want to reference model B (e.g. to join operations), and vice-versa. Therefore, export several A and B properties (the ones that does not depend on other modules) before use the "require" function may be a better answer. Jan 26, 2015 at 18:38
  • 25
    I also don't see circular dependencies as code smell. I'm developing a system where there are a few cases where it is needed. For example, modeling teams and users, where users can belong to many teams. So, it's not that something is wrong with my modeling. Obviously, I could refactor my code to avoid the circular dependency between the two entities, but that would not be the most pure form of the domain model, so I will not do that. Sep 6, 2016 at 11:02
  • 2
    This is not messy.. someone may want to brake a file to avoid a book of code i a single file. As node suggests you should add an exports = {} at the top of your code and then exports = yourData at the end of your code. With this practice you will avoid almost all errors from circular dependencies.
    – prieston
    Jan 29, 2018 at 11:11
  • 2
    Yet another legit reason two modules might depend on each other: they are written by different authors and should remain separate files because they have different roles in the system. Jan 4, 2019 at 23:13
62

[EDIT] it's not 2015 and most libraries (i.e. express) have made updates with better patterns so circular dependencies are no longer necessary. I recommend simply not using them.


I know I'm digging up an old answer here... The issue here is that module.exports is defined after you require ClassB. (which JohnnyHK's link shows) Circular dependencies work great in Node, they're just defined synchronously. When used properly, they actually solve a lot of common node issues (like accessing express.js app from other files)

Just make sure your necessary exports are defined before you require a file with a circular dependency.

This will break:

var ClassA = function(){};
var ClassB = require('classB'); //will require ClassA, which has no exports yet

module.exports = ClassA;

This will work:

var ClassA = module.exports = function(){};
var ClassB = require('classB');

I use this pattern all the time for accessing the express.js app in other files:

var express = require('express');
var app = module.exports = express();
// load in other dependencies, which can now require this file and use app
3
  • 3
    thank you for sharing the pattern and then further sharing how you commonly use this pattern when exporting out app = express()
    – user566245
    Feb 13, 2020 at 2:50
  • You recommend not using them, but i have an abstract class which needs to be extended on another file with a class, and also need to include that class in abstract class defined file to execute it as the main, i cant do anything but use circular for this i guess, thank you
    – C.Unbay
    Jul 2 at 13:33
  • Generally, libraries should not affect the node runtime in a way that modifies how node compilation unless the library is literally a compiler. yesterday
48

Sometimes it is really artificial to introduce a third class (as JohnnyHK advises), so in addition to Ianzz: If you do want to replace the module.exports, for example if you're creating a class (like the b.js file in the above example), this is possible as well, just make sure that in the file that is starting the circular require, the 'module.exports = ...' statement happens before the require statement.

a.js (the main file run with node)

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

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

var a = new ClassA();

module.exports = a;

b.js

var ClassB = function() {
}

ClassB.prototype.doSomethingLater() {
    util.log(a.property);
}

module.exports = ClassB;

var a = require("./a"); // <------ this is the only necessary change
4
  • thanks coen, I had never realized that module.exports had an effect on circular dependencies. Mar 13, 2013 at 18:23
  • this is especially useful with Mongoose (MongoDB) models; helps me to fix a problem when the BlogPost model has an array with references to comments, and each Comment model has reference to the BlogPost. Mar 26, 2019 at 18:40
  • this is the right answer for me for mongoose middleware implementations for related schemas. creating a third class as suggested by the accepted answer didn't really solve the problem as it still imports the classes implicitly.
    – Axel
    Mar 14, 2021 at 11:00
  • did not work for me, had to refactor to remove the cyclic dependency
    – Birla
    Oct 7, 2022 at 8:36
16

The solution is to 'forward declare' your exports object before requiring any other controller. So if you structure all your modules like this and you won't run into any issues like that:

// Module exports forward declaration:
module.exports = {

};

// Controllers:
var other_module = require('./other_module');

// Functions:
var foo = function () {

};

// Module exports injects:
module.exports.foo = foo;
2
  • 4
    Actually, this led me to simply use exports.foo = function() {...} instead. Definitely did the trick. Thanks!
    – zanona
    Nov 12, 2016 at 23:53
  • 3
    I'm not sure what you're proposing here. module.exports is already a plain Object by default, so your "forward declaration" line is redundant.
    – ZachB
    Apr 21, 2020 at 18:34
11

You can solve this easily: just export your data before you require anything else in modules where you use module.exports:

classA.js

class ClassA {

    constructor(){
        ClassB.someMethod();
        ClassB.anotherMethod();
    };

    static someMethod () {
        console.log( 'Class A Doing someMethod' );
    };

    static anotherMethod () {
        console.log( 'Class A Doing anotherMethod' );
    };

};

module.exports = ClassA;
var ClassB = require( "./classB.js" );

let classX = new ClassA();

classB.js

class ClassB {

    constructor(){
        ClassA.someMethod();
        ClassA.anotherMethod();
    };

    static someMethod () {
        console.log( 'Class B Doing someMethod' );
    };

    static anotherMethod () {
        console.log( 'Class A Doing anotherMethod' );
    };

};

module.exports = ClassB;
var ClassA = require( "./classA.js" );

let classX = new ClassB();
0
11

the extremely simple solution is often:

usually you'd have the require at the top of the file ...

var script = require('./script')
function stuff() {
      script.farfunction()
}

instead, just require it "in the function"

function stuff() {
      var _script = require('./script')
      _script.farfunction()
}
10

What about lazy requiring only when you need to? So your b.js looks as follows

var ClassB = function() {
}
ClassB.prototype.doSomethingLater() {
    var a = require("./a");    //a.js has finished by now
    util.log(a.property);
}
module.exports = ClassB;

Of course it is good practice to put all require statements on top of the file. But there are occasions, where I forgive myself for picking something out of an otherwise unrelated module. Call it a hack, but sometimes this is better than introducing a further dependency, or adding an extra module or adding new structures (EventEmitter, etc)

2
  • And sometimes it's critical when dealing with a tree data structure with child objects maintaining references to a parent. Thanks for the tip. Feb 10, 2019 at 1:54
  • I wouldn't call this a hack. This is completely valid, and just because people think you should put every require at the top of the page, it's absolutely not a _require_ment.
    – Jack_Hu
    Apr 11, 2022 at 0:31
8

A solution which require minimal change is extending module.exports instead of overriding it.

a.js - app entry point and module which use method do from b.js*

_ = require('underscore'); //underscore provides extend() for shallow extend
b = require('./b'); //module `a` uses module `b`
_.extend(module.exports, {
    do: function () {
        console.log('doing a');
    }
});
b.do();//call `b.do()` which in turn will circularly call `a.do()`

b.js - module which use method do from a.js

_ = require('underscore');
a = require('./a');

_.extend(module.exports, {
    do: function(){
        console.log('doing b');
        a.do();//Call `b.do()` from `a.do()` when `a` just initalized 
    }
})

It will work and produce:

doing b
doing a

While this code will not work:

a.js

b = require('./b');
module.exports = {
    do: function () {
        console.log('doing a');
    }
};
b.do();

b.js

a = require('./a');
module.exports = {
    do: function () {
        console.log('doing b');
    }
};
a.do();

Output:

node a.js
b.js:7
a.do();
    ^    
TypeError: a.do is not a function
1
  • 4
    If you don't have underscore, then ES6's Object.assign() can do the same work that _.extend() is doing in this answer. Jan 2, 2017 at 6:57
8

The important thing is not to re-assign the module.exports object that you have been given, because that object may have already been given to other modules in the cycle! Just assign properties inside module.exports and other modules will see them appear.

So a simple solution is:

module.exports.firstMember = ___;
module.exports.secondMember = ___;

The only real downside is the need to repeat module.exports. many times.


Similar to lanzz and setec's answers, I have been using the following pattern, which feels more declarative:

module.exports = Object.assign(module.exports, {
    firstMember: ___,
    secondMember: ___,
});

The Object.assign() copies the members into the exports object that has already been given to other modules.

The = assignment is logically redundant, since it is just setting module.exports to itself, but I am using it because it helps my IDE (WebStorm) to recognise that firstMember is a property of this module, so "Go To -> Declaration" (Cmd-B) and other tooling will work from other files.

This pattern is not very pretty, so I only use it when a cyclic dependency issue needs to be resolved.

It is fairly well suited to the reveal pattern, because you can easily add and remove exports from the object, especially when using ES6's property shorthand.

Object.assign(module.exports, {
    firstMember,
    //secondMember,
});
1
  • "not to re-assign the module.exports object that you have been given, because that object may have already been given to other modules" might be the reason, tks
    – Dan D.
    May 10, 2022 at 14:36
6

An other method I've seen people do is exporting at the first line and saving it as a local variable like this:

let self = module.exports = {};

const a = require('./a');

// Exporting the necessary functions
self.func = function() { ... }

I tend to use this method, do you know about any downsides of it?

1
  • 1
    you can rather do module.exports.func1 = , module.exports.func2 = Sep 26, 2019 at 6:06
6

TL;DR

Just use exports.someMember = someMember instead of module.exports = { // new object }.

Extended Answer

After reading lanzz's response I could finally figure it out what is happening here, so I'll give my two cents on the subject, extending his answer.

Let's see this example:

a.js

console.log("a starting");

console.log("a requires b");
const b = require("./b");
console.log("a gets b =", b);

function functionA() {
  console.log("function a");
}

console.log("a done");
exports.functionA = functionA;

b.js

console.log("b starting");

console.log("b requires a");
const a = require("./a");
console.log("b gets a =", a);

function functionB() {
  console.log("On b, a =", a)
}

console.log("b done");
exports.functionB = functionB;

main.js

const a = require("./a");
const b = require("./b");

b.functionB()

Output

a starting
a requires b
b starting
b requires a
b gets a = {}
b done
a gets b = { functionB: [Function: functionB] }
a done
On b, a = { functionA: [Function: functionA] }

Here we can see that at first b receives an empty object as a, and then once a is fully loaded, that reference is updated through exports.functionA = functionA. If you instead replace the entire module with another object, through module.exports, then b will lose the reference from a, since it will point out to the same empty object from the beginning, instead of pointing to the new one.

So if you export a like this: module.exports = { functionA: functionA }, then the output will be:

a starting
a requires b
b starting
b requires a
b gets a = {}
b done
a gets b = { functionB: [Function: functionB] }
a done
On b, a = {} // same empty object
4

Actually I ended up requiring my dependency with

 var a = null;
 process.nextTick(()=>a=require("./a")); //Circular reference!

not pretty, but it works. It is more understandable and honest than changing b.js (for example only augmenting modules.export), which otherwise is perfect as is.

2
  • Of all the solutions on this page, this is the only one that solved my problem. I tried each in turn.
    – Joe Lapp
    Oct 17, 2017 at 22:35
  • This is the only solution that actually works for me. I've been trying to find a solution for this for days. Thank you so much! Oct 10, 2022 at 22:13
3

Here is a quick workaround that I've found use full.

On file 'a.js'

let B;
class A{
  constructor(){
    process.nextTick(()=>{
      B = require('./b')
    })
  } 
}
module.exports = new A();

On the file 'b.js' write the following

let A;
class B{
  constructor(){
    process.nextTick(()=>{
      A = require('./a')
    })
  } 
}
module.exports = new B();

This way on the next iteration of the event loop classes will be defined correctly and those require statements will work as expected.

5
  • this is not a solution. this is just a scape plan. but it is fun Oct 3, 2020 at 15:43
  • @mohammadjawadBarati - "this is not a solution". It is an answer to a problem, how is that not a solution?
    – AlexJBallz
    Nov 25, 2020 at 21:23
  • @AlexJBallz because you just require b in the nextTick & this is not the right way. s/he must change his/her coding style to another way. if your code requires something earlier than it should require it, it's wrong. you should manage it to don't face this problem or anything like this Nov 30, 2020 at 12:11
  • @mohammadjawadBarati Sounds like you're a bit close minded, your way or the highway kind of mantra going on here. Its a solution, it works, if it works and provides the expected result, its not wrong, thats what a solution is. There can be multiple solutions to the same problem, you don't have to like it. Everyone has their own style.
    – AlexJBallz
    Nov 30, 2020 at 17:10
  • This eliminates the ability to have static methods on the class.
    – Jeff Ryan
    Apr 14, 2021 at 19:03
0

One way to avoid it is to don't require one file in other just pass it as an argument to a function what ever you need in an another file. By this way circular dependency will never arise.

2
  • I would expect it to be fairly common for one module to need to reference another.
    – JCutting8
    May 8, 2022 at 16:32
  • Yes, we take dependencies and inject them in the respective functions, dependency injection. May 5 at 5:51
-5

If you just can't eliminate circular dependencies (e.g useraccount <---> userlogin), there's one more option...

Its as simple as using setTimeout()

//useraccount.js

let UserLogin = {};

setTimeout(()=>UserLogin=require('./userlogin.js'), 10);

class UserAccount{
 
getLogin(){
return new UserLogin(this.email);

}

}



//userlogin.js

let UserAccount ={};

setTimeout(()=>UserAccount=require('./useraccount.js'), 15);


class UserLogin{

getUser(){

return new User(this.token);

}

}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.