Node.js / Express Response Event

I am trying to create middleware that records response time and status codes and sends it to the database. However, I am not sure which event to use. There is a close event in node documentation, but it never fires. end doesn't work either. However, header does, but I cannot find any documentation.

 app.use(function(req, res, next) { res.on('close', function() { console.log('close') }) res.on('end', function() { console.log('end') }) res.on('header', function() { console.log('header') console.log(res.statusCode) }) next() }) 

Only the header executed and it returns the correct res.statusCode file.

My questions:

  • Why is there no close arrow? Why shooting header ?
  • Is this a reliable way?
+4
source share
2 answers

close event is fired only if the connection was completed before calling response.end (). header event shot by connect . This is not node.js native http.ServerResponse event.

Take a look at connect responseTime middleware. I think this should help you.

Update

Here's the header event documentation https://github.com/senchalabs/connect/blob/gh-pages/tests.md#patch

heder fired from writeHead method, proxied by connect https://github.com/senchalabs/connect/blob/master/lib/patch.js

+3
source

There is an event to complete the event , it is issued when a response is sent.

 app.use(function(req, res,next){ res.on('finish', function(){ console.log('the response has been sent'); }); next(); }); 
+2
source

All Articles