Javascript Node.js-使app.js中的数组在模块中可用
在我的节点app.js中,我不需要让我的数组Javascript Node.js-使app.js中的数组在模块中可用,javascript,node.js,Javascript,Node.js,在我的节点app.js中,我不需要让我的数组openConnectionsglobal…但我希望它在app.js中,并且可以通过模块sseu server.js访问sseStart功能。我该怎么做 app.js: var express = require('express'); var morgan = require('morgan'); var fs = require("fs"); var createDomain = require("domain").create; var app
openConnections
global…但我希望它在app.js中,并且可以通过模块sseu 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中需要它。我想把
openConnections
放在sse_start.js中。如果我这样做了,我想我也需要导出openConnections
,并在app.js中需要它?因为我担心的是它会从内存中删除,而不会保留在内存中。这不是问题,您可以将它移动到sse_start并导出它。它不会从内存中删除。