Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js / Express on response event

Tags:

node.js

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:

  1. Why isn't close firing? Why is header firing?
  2. Is this a reliable way to go?
like image 455
Jonathan Ong Avatar asked Sep 02 '12 21:09

Jonathan Ong


People also ask

How do I get response time in Express?

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() .

How do I trigger an event in Node JS?

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.

What is Express () in node JS?

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.

How do I send a status code in response Nodejs?

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.


2 Answers

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();
});
like image 149
Vova Litichevskyi Avatar answered Oct 09 '22 22:10

Vova Litichevskyi


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

like image 44
Vadim Baryshev Avatar answered Oct 09 '22 21:10

Vadim Baryshev