当res.flush()不起作用时,我如何刷新事件流?(node . js)



我使用express和node.js

我已经工作了很长时间的加载条的工作,我终于想出了使用res.flush(),因为res.write()不工作由于压缩中间件(以我的理解)。

现在当我把它上传到服务器时,我遇到了同样的问题。流不会刷新,加载条只在res.end()上更新。所有其他应该连续发送的进度也通过res.end()发送(一次性发送)。由于res.flush()不像在我的pc上工作,我不知道该怎么做,因为我无法在服务器上调试。

我有一个EventSource在客户端监听更新,使加载条,但在实时服务器上唯一的更新是当res.end()被调用。

router.get('/statistics/:query/', function(req, res) {
let query = req.params.query;
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive'
})

//I have absolutely no idea if this is how to transfer progress between two classes
//If this can be improved please let me know
//The goal is to send updates back to the router, while the static class is querying the database    
let progressObject : any = new Object();
progressObject.progress = 0;

progressObject.update = function(newProgress) { 
//The update function is called within the static class "Statistics" as database query is handled

let isDone = Math.round(newProgress) == 100 ? true : null; //sets isDone to true if progress=100
this.progress = newProgress;
res.write("data: "+JSON.stringify(this)+"nn"); //This is the real problem! It works on my PC
res.flush(); //But on the server it is only sent on res.end() in the bottom
}
let barChartLabels = Statistics.getBarChartLabels(progressObject, query);
barChartLabels.then(labels =>{
let responseObject = {
message : labels,
progress : null,
chartTitle : "Stats", 
success : true,
};
res.write("data: "+JSON.stringify(responseObject)+"nn");
res.end() //All progress data is only flushed here.
}).catch(err=>{
console.log("error!: "+err)
let responseObject = {
message : "Something went wrong when querying the database",
progress : null,
success : false
};
res.write("data: "+JSON.stringify(responseObject)+"nn");
res.end()
})
});

最重要的是让这个在服务器上工作,但我也很感兴趣的是知道一个好的方法来发送加载进度到路由器是什么。

在斯蒂尔·帕克的帮助下,我设法解决了这个问题。

生产服务器在iis上运行,我所要做的就是将responsebufferlimit =0设置为默认值4194304。

可以添加

<handlers>
<add name="iisnode" path="app.js" verb="*" modules="iisnode" responseBufferLimit="0" />
</handlers>

到web。配置文件。

最新更新