[英]Ordering of require() seems to affect modules
I'm writing a very basic Node app with three components: index.js, mqtt.js, slack.js. 我正在编写一个非常基本的Node应用程序,其中包含三个组件:index.js,mqtt.js,slack.js。 The mqtt and slack modules both expose some of their methods with module.exports.
mqtt和slack模块都使用module.exports公开了一些方法。 However, I can only expose the files in one direction.
但是,我只能向一个方向公开文件。 Code sample:
代码示例:
index.js: index.js:
var slack = require('./slack');
var mqtt = require('./mqtt');
var client;
mqtt.connectMQTT(client);
slack.startServer();
slack.js: slack.js:
var mqtt = require('./mqtt');
module.exports = {
startServer: function() { //blahblah },
postToSlack: function() { //blahblah }
};
mqtt.js: mqtt.js:
var slack = require('./slack');
module.exports = {
connectClient: function() { //blahblah },
handleMessage: function() { slack.postToSlack(); }
};
Now, when I try to call postToSlack() from mqtt.js, Node gives me: TypeError: Object # has no method 'postToSlack' 现在,当我尝试从mqtt.js调用postToSlack()时,Node给了我:TypeError:对象#没有方法'postToSlack'
BUT, when I swap the line position of the two require()'s in index.js, now I can call methods from mqtt but not from slack. 但是,当我在index.js中交换两个require()的行位置时,现在可以从mqtt调用方法,而不能从slack调用方法。 The error has mirrored itself.
该错误已反映出来。 I can call methods from index.js just fine.
我可以从index.js调用方法。
Should I be using callbacks to hold off running any code until all of my modules have successfully been loaded? 我应该使用回调来推迟运行任何代码,直到成功加载所有模块吗? Why does the order of require() in a completely separate file affect exposing methods?
为什么完全独立文件中的require()顺序会影响公开方法?
You have a circular dependency between slack.js
and mqtt.js
. 您在
slack.js
和mqtt.js
之间具有循环依赖关系。 Read the node.js docs on require cycles for details, but the correct solution to this situation is usually to remove the circular dependency entirely. 阅读require周期上的node.js文档以了解详细信息,但是这种情况的正确解决方案通常是完全删除循环依赖项。 It is an indicator that your design coupling is not quite right yet.
这表明您的设计耦合还不太正确。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.