I'm trying to create a middleware that logs response times and status codes and sends it to a database. However, I'm not sure what event to use. In node's documentation there's a close event but it is never fired. end doesn't work either. However, header does, but I can't 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 header fires, and it does return the correct res.statusCode.
My questions:
close firing? Why is header firing?We can get the response time in the response header of a request with the response-time package. It has a responseTime function which returns a middleware that we can use with the use method of express or express. Router() .
Emitting events: Every event is named event in nodejs. We can trigger an event by emit(event, [arg1], [arg2], […]) function. We can pass an arbitrary set of arguments to the listener functions.
Express is a node js web application framework that provides broad features for building web and mobile applications. It is used to build a single page, multipage, and hybrid web application. It's a layer built on the top of the Node js that helps manage servers and routes.
The res. sendStatus() function is used to set the response HTTP status code to statusCode and send its string representation as the response body. Parameter: The statusCode parameter describes the HTTP status code. Returns: It returns an Object.
There is an finish event, it is emitted when the response has been sent.
app.use(function(req, res,next){
    res.on('finish', function(){
        console.log('the response has been sent');
    });
    next();
});
                        close event emited only if connection was terminated before response.end() called.
header event fired by connect. This is not node.js http.ServerResponse native event.
Look at connect responseTime middleware. I think it should help you.
Update:
Here is 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With