我有两个不同的节点脚本...... save_info.js
从openConections array
导入sse_server.js
。并且sse_server.js
从function broadcast
导入save_info.js
。
但是,这导致openConnections array
在undefined
内save_info.js
。为什么会这样,我该如何解决这个问题?
save_info.js:
var openConnections = require('../scripts/sse_server.js').openConnections;
function broadcast(result, event, httpObject) {
var result = JSON.stringify(result);
var date = new Date().getMilliseconds();
httpObject.write('id: ' + date + '\n');
httpObject.write('data: { \"' + event + '\":\n');
httpObject.write('data:' + result + '\n');
httpObject.write('data: }' + '\n\n');
}
function db_finish(err, product, numberAffected,
result, event) {
if (err) { console.log(err) }
else {
console.log("Db insert successfull");
openConnections.forEach(function(httpObject) {
broadcast(result, event, httpObject);
});
}
console.log("Numer effected " + numberAffected);
}
module.exports.openConnections = openConnections;
sse_server.js:
var broadcast = require("../data/save_info").broadcast;
var openConnections = [];
for (var model in models){
models[model].find({}).sort({_id: -1}).limit(1).exec(
function (err, result){
broadcast(result, model, res);
});
}
module.exports.broadcast = broadcast;
答案 0 :(得分:1)
为了防止循环依赖,nodejs模块加载器停止在save_info.js中加载sse_server模块这就是未定义openConnections的原因。要解决此问题,请执行以下操作:
1)将broadcast()移出到一个单独的模块(例如broadcast.js)。
2)在sse_server.js和save_info.js中放置require(' ../ data / broadcast.js')
3)删除sse_server.js中的require(' ../ data / save_info')