Why can I execute code after “res.send”?

Sure end ends the HTTP response, but it doesn’t do anything special to your code.

You can continue doing other things even after you’ve ended a response.

What you can’t do, however, is do anything useful with res. Since the response is over, you can’t write more data to it.

res.send(...);
res.write('more stuff'); // throws an error since res is now closed

This behavior is unlike other traditional frameworks (PHP, ASP, etc) which allocate a thread to a HTTP request and terminate the thread when the response is over. If you call an equivalent function like ASP’s Response.End, the thread terminates and your code stops running. In node, there is no thread to stop. req and res won’t fire any more events, but the code in your callbacks is free to continue running (so long as it does not attempt to call methods on res that require a valid response to be open).

Leave a Comment