@app = express.createServer()
@app.use express.bodyParser()
At the end of an HTTP request/response, I want to perform an action (to close a database connection). This would preferably occur after the the response is on its way to the client so the client isn't waiting on it, but if it would occur inline, I can always do a process.nextTick.
How can I register a callback for the end of the response?
The HTTP response is a WritableStream. When the stream closes, a finish event is emitted. Thus listening to it does the trick:
res.on('finish', function() {
console.log(res._headers);
});
Much more flexible. Can be put in a middleware or a resource handler.
So you want to open/close/open/close a connection to the database with each request? It's much better to keep it open and just reuse the connection.
If you do want to do something just after you send the response back to the client (for all routes) you can make a middleware that overrides the res.end()
function (that's the last one called , like such:
@app.use (req, res, next) ->
var oldEnd = res.end;
res.end = ->
oldEnd.apply(res, arguments)
# do stuff after sending the response back to the client