Check if res is sent / ended with Express
Asked Answered
C

2

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.

Cleodell answered 23/8, 2019 at 0:0 Comment(2)
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.Autosome
thanks for that tip @Autosome that sounds about rightCleodell
S
4

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

Slacken answered 23/8, 2019 at 0:9 Comment(4)
What if the response is closed from the other side?Alexandraalexandre
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.Slacken
res.finished is deprecated, you can use response.writableEnded or request.writableFinished depending what you want.Slimsy
@Slimsy 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.Slacken
B
12

Use res.writableEnded (docs).

res.finished is deprecated (see).

Blackfish answered 4/6, 2020 at 0:41 Comment(1)
Well, res.writableEnded is not working for my in latest (2022) Express and latest node (16).Indult
S
4

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

Slacken answered 23/8, 2019 at 0:9 Comment(4)
What if the response is closed from the other side?Alexandraalexandre
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.Slacken
res.finished is deprecated, you can use response.writableEnded or request.writableFinished depending what you want.Slimsy
@Slimsy 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.Slacken

© 2022 - 2024 — McMap. All rights reserved.