繁体   English   中英

Node.js-使app.js中的数组在模块中可用

[英]Node.js- Make array in app.js available in a module

在我的Node app.js中,不需要全局设置数组openConnections ...但是我希望在app.js中使用它,并且可以通过sse_server.js模块访问sseStart函数。 我怎样才能做到这一点?

app.js:

var express = require('express');
var morgan = require('morgan');
var fs = require("fs");
var createDomain = require("domain").create;
var app = express();



app.use(express.static(__dirname + '/app/static/views'));
app.use(express.static(__dirname + '/app/static'));
app.use(express.static(__dirname + '/app/images'));
app.use(express.static(__dirname + '/app'));

var openConnections = [];
var sseStart = require(__dirname + '/app/scripts/sse_server.js');

app.get('/subscribe', sseStart);

var callAllApiAndSave = require('./app/scripts/api_scripts/call_all_api.js');
var db = require(__dirname + '/app/data/db.js');

var mainDomain = new createDomain();

mainDomain.run(function () {
    mainDomain.on('error', function() {
        console.log('yoyoyoyoyoyoyoyoyoyoyoyoyoyoyo');
    });
    mainDomain.on('error', function(er) {
        console.log('error, but oh well', er.message);
    });
    db.connectDatabase();
    setInterval(callAllApiAndSave, 120000);
    var server = app.listen(9000, function() {
            console.log('Listening on port %d', server.address().port);
    });
});

sse_start.js:

function sseStart(req, res) {
    console.log(req);
    // set timeout as high as possible
    req.socket.setTimeout(Infinity);

    // send headers for event-stream connection
    // see spec for more information
    res.writeHead(200, {
        'Content-Type': 'text/event-stream',
        'Cache-Control': 'no-cache',
        'Connection': 'keep-alive'
    });
    res.write('\n');

    // push this res object to our global variable
    console.log("Creating SSE connection for " + req.connection.remoteAddress);
    openConnections.push(res);
    console.log("Total current live connections: " +
                openConnections.length);

    // When the request is closed, e.g. the browser window
    // is closed. We search through the open connections
    // array and remove this connection.
    req.on("close", function() {
        console.log("Closing SSE connection for "
                    + req.connection.remoteAddress);
        openConnections = openConnections.filter(function(storedRes) {
            if (storedRes !== res) {
                return storedRes;
            }
        });
        if (!openConnections)  openConnections = [];

        console.log("Total current live connections: " +
                    openConnections.length);
    });
}

module.exports = sseStart;

查看您发布的openConnections代码仅在sse_start.js中使用,那么为什么不把它放在那里?

如果您确实要在这两个文件之间共享该数组,则可以将其放在单独的模块中,并在app.js和sse_start.js中要求它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM