Node.js server keeps streaming data even after cli

2019-09-07 06:20发布

I have a small Node.js + express server which has a dummy download method:

app.get("/download",function(req,res) {

    res.set('Content-Type', 'application/octet-stream');
    res.set('Content-Length', 1000000000011);
    res.set('Connection', 'keep-alive');
    res.set('Content-Disposition', 'attachment; filename="file.zip"');

    var interval = setInterval(function(){
        res.write(00000000);
        var dateStr = new Date().toISOString();
        console.log(dateStr + " writing bits...");
    },500);
});

The problem is that after I close the browser I still see that the node server is transferring data. How can I detect when the client is disconnected and stop the streaming?

I tried to use:

req.on("close", function() {
    console.log("client closed");
});

req.on('error', function(e) {
  console.log('problem with request: ' + e.message);
});

But without luck. Any help will be appreciated.

1条回答
戒情不戒烟
2楼-- · 2019-09-07 06:54

The browser won't send an http request to the server when it closes, and I couldn't find anything in the Node.js docs about a close event on the request object. However, I have set something up similar to this using Socket.io. This example pushes a random number to the client every second, and stops pushing data after the client disconnects:

io.on('connection', function(socket) {
  var intervalID = setInterval(function () {
    socket.emit('push', {randomNumber: Math.random()});
  }, 1000);
  socket.on('disconnect', function () {
    clearInterval(intervalID);
  });
}

Here's how you set up Socket.io with Express.

查看更多
登录 后发表回答