0

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.

Stasel
  • 1,257
  • 1
  • 12
  • 22

1 Answers1

0

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.

Nocturno
  • 7,946
  • 5
  • 29
  • 39