How to deal with cyclic dependencies in Node.js

后端 未结 13 1966
别那么骄傲
别那么骄傲 2020-11-22 04:36

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 b

13条回答
  •  遇见更好的自我
    2020-11-22 05:04

    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
    

提交回复
热议问题