'In a node js http server how to know when an http exchange ended?

I'm writing an http server application in node js. I want to have an event that triggers when an http exchange is over but I couldn't figure out how to do it. I tried to do it the way it would be done with other streams in node js using .on('end', callback) but it doesn't seem to work:

what I tried (which doesn't work):

const Http = require('http');

const httpServer = Http.createServer((httpRequest, httpResponse) => {
    console.log('<started>');
    httpResponse.on('end', () => console.log('<ended>'));
    httpResponse.end('END');
    console.log('<finished>');
});
httpServer.listen(80);

what I expect my console to print after navigating to localhost in my browser:

<started>
<finished>
<ended>

what I really get:

<started>
<finished>

How to do this correctly? I want a callback that triggers when the server finished streaming the response stream for this http request to the client.



Solution 1:[1]

httpResponse is a http.IncomingMessage, you can listen to close event (instead of end), the event will be emitted when the request has been completed.

const Http = require('http');

const httpServer = Http.createServer((httpRequest, httpResponse) => {
  console.log('<started>');
  httpResponse.on('close', () => console.log('<ended>'));
  httpResponse.end('END');
  console.log('<finished>');
});
httpServer.listen(80);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 hoangdv