无法在NodeJS

时间:2016-01-10 17:38:26

标签: javascript node.js

将其分解并简化一下:想象一下,我的项目中有三个文件。一个main.js和两个模块:moduleA.js和moduleB.js。 main.js访问moduleA.js,它从moduleB.js调用一个函数。现在,moduleB.js发现它需要一个仅在moduleA.js中可用的信息。当然,moduleB.js尝试访问moduleA.js中的一个函数,该函数在技术上能够将此信息提供给moduleB.js,但是存在错误。

这是简化的代码。

main.js

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

console.log(a.respond());

moduleA.js

var b = require("./moduleB.js");

module.exports = {
    respond: function(){
        return b.returnAnswerForModuleA();
    },
    getSomeInformationOnlyAvailableInA: function(){
        return "This is the information we need!";
    }
};

moduleB.js

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

module.exports = {
  returnAnswerForModuleA: function(){
      return a.getSomeInformationOnlyAvailableInA()
  }
};

以下是错误消息:

/Users/Tim/Code/ChatBot/test/moduleB.js:5
      return a.getSomeInformationOnlyAvailableInA()
               ^

TypeError: a.getSomeInformationOnlyAvailableInA is not a function
    at Object.module.exports.returnAnswerForModuleA (/Users/Tim/Code/ChatBot/test/moduleB.js:5:16)
    at Object.module.exports.respond (/Users/Tim/Code/ChatBot/test/moduleA.js:5:18)
    at Object.<anonymous> (/Users/Tim/Code/ChatBot/test/main.js:3:15)
    at Module._compile (module.js:425:26)
    at Object.Module._extensions..js (module.js:432:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:311:12)
    at Function.Module.runMain (module.js:457:10)
    at startup (node.js:136:18)
    at node.js:972:3

为什么我无法从moduleB.js访问moduleA.js?

重组我的代码不是一个真正的选择!

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

这看起来像node.js中循环依赖的问题,其中循环依赖导致一个模块被解析为空对象(从而导致您看到的错误)。请参阅以下文章解释:

Node.js and circular dependencies

Circular dependencies in Node.js

第一篇文章提供了两种可能的解决方案:“延迟调用依赖直到运行时”和“用依赖注入替换循环依赖”。

我认为您可以通过将模块B更改为此来解决循环问题:

var moduleA;

module.exports = {
  returnAnswerForModuleA: function(){
      if (!moduleA) {
          moduleA = require("./moduleA.js");
      }
      return moduleA.getSomeInformationOnlyAvailableInA()
  }
};

这延迟了模块B中模块A的加载,直到运行时,它已经成功加载并且在模块缓存中,从而避免了循环依赖。

相关问题