7

Using Express, how can I determine the response has been sent / that the response has been completely written to?

app.use((req,res,next) => {

   if(res.ended){
     //
   }

   if(res.finished){
     //
   }

});

how can I tell if res.end() has been called? I am looking for a boolean I can read on res.

  • 1
    Keep in mind that the usual way of programming Express is that you don't call `next()` after you call `res.send()` so a middleware like you show above that you put at the end of the middleware chain would never get called. – jfriend00 Aug 23 '19 at 00:25
  • thanks for that tip @jfriend00 that sounds about right –  Aug 23 '19 at 00:40

2 Answers2

11

Use res.writableEnded (docs).

res.finished is deprecated (see).

vitaliydev
  • 420
  • 4
  • 7
4

response.end() will set response.finished if it's been called, as per the documentation.

tadman
  • 208,517
  • 23
  • 234
  • 262
  • What if the response is closed from the other side? – Tomáš Zato Feb 25 '20 at 11:29
  • I'm not sure what the current behaviour in Express is, so you may need to experiment. A different event is emitted and no further callbacks are made, far as I know, but each callback gets to run to completion. – tadman Feb 25 '20 at 17:11
  • 4
    res.finished is deprecated, you can use response.writableEnded or request.writableFinished depending what you want. – AndyJRR Feb 25 '20 at 20:31
  • 1
    @AndyJRR If this answer is out of date and you know how it works in the current Express it may be worth posting an alternate answer. – tadman Feb 25 '20 at 21:53