21

I am using express with node.js for a http server. I store the response object so I can stream events down to the client on that channel. Is there a way to detect when the client disconnects? When I kill my client I can still write to the response object without getting any kind of exception/error. It looks like the service keeps the underlying tcp channel open as long as I keep writing to the response object.

Jeroen
  • 507
  • 1
  • 5
  • 15

1 Answers1

48
req.on("close", function() {
  // request closed unexpectedly
});

req.on("end", function() {
  // request ended normally
});
unsynchronized
  • 4,609
  • 2
  • 29
  • 40
Raynos
  • 156,883
  • 55
  • 337
  • 385
  • nice this is new for me also :) – Alfred Jul 04 '11 at 15:28
  • @Alfred ._. you are _Alfred_. I mean _the Alfred_ shame on you for not reading the nodejs docs. – Raynos Jul 04 '11 at 15:44
  • Note: 'close' can fire after 'end', but not vice versa. I'm confused. How can close be emitter after end? I can only imagine it vice versa. User dropped connection, but for example request to mysql already sent. – Somebody Apr 12 '12 at 11:21
  • both not happening when we switch off wifi. client showing disconnected, but server still connected giving `unavailable-id` in peerjs server – Phaneendra Charyulu Kanduri Jan 04 '16 at 03:47
  • @PhaneendraCharyuluKanduri i'm in the same boat now, close triggers if the browser or the tab is closed but if there is an unexpected interruption then it is not triggered. wondering is there any handler that we can leverage. – Sai Oct 19 '16 at 21:50
  • 4
    On node 12 `close` event is fired in the end anyways – Naveen Apr 22 '20 at 16:27