Why can I execute the code after "res.send"?

I am wondering what is the mechanics behind the behavior of the following code:

res.send(200, { data: 'test data' }); console.log('still here...'); 

I understand that res.send does not return a function, but closes the connection / terminates the request. This may explain why I can still execute the code after the res.send (I looked at the express source and does not seem to be an asynchronous function).

Is there anything else in the game that might be missing?

+46
express
Apr 23 '13 at 22:54
source share
2 answers

Sure end completes the HTTP response, but it does nothing special for your code.

You can continue to do other things even after you have finished the answer.

However, you cannot do anything useful with res . Since the answer is complete, you cannot write more data to it.

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

This behavior is different from other traditional frameworks (PHP, ASP, etc.) that allocate a stream for an HTTP request and terminate the stream when the response is complete. If you call an equivalent function, such as ASP Response.End , the thread terminates and your code stops working. There is no thread to stop in node. req and res will no longer fire events, but the code in your callbacks may continue to work (until it tries to call res methods that require a valid response to be open).

+73
Apr 23 '13 at 22:58
source share

Edit: I no longer do what is explained below, since you should not return a value when this is not necessary. This makes your code less readable and looks hacked. Instead, I suggest separating the return statement from res.send() . @slavafomin explained this well in the comments.

An easy way to stop the execution of a function and send a response at one time is

 return res.send('500', 'Error message here'); 

This allows you to use short if to handle errors such as:

 if (err) { return res.send('500', 'Error message here'); } 

The exact return of the res.send function is an object that seems to contain the entire state of the connection after it has ended (request, status, headers, etc.), but this should not matter, since you won’t do anything with it .

+32
Jul 30 '14 at 13:37
source share



All Articles