Jonathan Ong
Jonathan Ong

Reputation: 20315

Node.js / Express on response event

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?

Upvotes: 20

Views: 34747

Answers (2)

Vadim Baryshev
Vadim Baryshev

Reputation: 26189

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

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

Upvotes: 11

Vova Litichevskyi
Vova Litichevskyi

Reputation: 443

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();
});

Upvotes: 36

Related Questions