Jonathan Ong Jonathan Ong - 4 months ago 37
Node.js Question

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?


Answer

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