我有2个不同的节点脚本... save_info.jsopenConections array导入sse_server.js。并且,sse_server.jsfunction broadcast导入save_info.js
但是,这导致openConnections arrayundefined内部成为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;

最佳答案

为了防止循环依赖性,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')

10-06 12:36