Runcible
Runcible

Reputation: 3098

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 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?

Upvotes: 234

Views: 179552

Answers (16)

Fattie
Fattie

Reputation: 12631

NOTE THAT THE TOTALLY CORRECT ANSWER IS GIVEN BY CAMILO:

// DO NOT DO THIS
// module.exports = {
//     tell, devTell, devTellPermanentLog,
//     updateAdmin
// }

// DO THIS:
exports.tell = tell
exports.devTell = devTell
exports.devTellPermanentLog = devTellPermanentLog
exports.updateAdmin = updateAdmin

It's incredible that for the literally 100s of thousands of words written about circulars in node.js, that is the whole solution.

That's all there is to it.

Thank you, Camilo.


Here is a quick workaround that is worth knowing, if you don't have time to refactor:

An extremely simple "quick solution" if you just need something to run immediately is:

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()
}

Upvotes: 13

lanzz
lanzz

Reputation: 43168

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.

Upvotes: 206

Camilo
Camilo

Reputation: 726

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

Upvotes: 7

Tom
Tom

Reputation: 41

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);

}

}

Upvotes: -5

joeytwiddle
joeytwiddle

Reputation: 31285

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,
});

Upvotes: 7

sagar saini
sagar saini

Reputation: 107

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.

Upvotes: 0

Melik Karapetyan
Melik Karapetyan

Reputation: 94

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.

Upvotes: 3

Giuseppe Canale
Giuseppe Canale

Reputation: 525

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();

Upvotes: 10

Bence Gedai
Bence Gedai

Reputation: 1511

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?

Upvotes: 6

zevero
zevero

Reputation: 2402

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.

Upvotes: 4

zevero
zevero

Reputation: 2402

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)

Upvotes: 12

setec
setec

Reputation: 16090

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

Upvotes: 8

Will Stern
Will Stern

Reputation: 17579

[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

Upvotes: 63

Nicolas Gramlich
Nicolas Gramlich

Reputation: 2790

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;

Upvotes: 16

JohnnyHK
JohnnyHK

Reputation: 311865

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.

Upvotes: 130

Corno
Corno

Reputation: 5396

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

Upvotes: 47

Related Questions