21

ExpressJS middleware req, res, next have hooks like .on and .pipe.

But I'm looking for hooks for the app.get and app.post methods.

1 Answer 1

55

app.use() and middleware can be used for "before" and a combination of the 'close' and 'finish' events can be used for "after."

app.use(function (req, res, next) {
    function afterResponse() {
        res.removeListener('finish', afterResponse);
        res.removeListener('close', afterResponse);

        // action after response
    }

    res.on('finish', afterResponse);
    res.on('close', afterResponse);

    // action before request
    // eventually calling `next()`
});

app.use(app.router);

An example of this is the logger middleware, which will append to the log after the response by default.

Just make sure this "middleware" is used before app.router as order does matter.

7
  • It's also interesting, that logger listens to both close and finish. Supposedly that can be useful in some situations. Nov 24, 2013 at 18:19
  • @vkurchatkin Using both can help with backwards compatibility as 'finish' is new with Node 0.10 and Streams2. So, Express is using 'close' as well to support lower versions of Node. Nov 24, 2013 at 18:24
  • Hmm, don't think so: nodejs.org/api/http.html#http_event_close_1, nodejs.org/api/stream.html#stream_event_finish. Looks like close is emitted if connection was terminated berfore res.end() call and finish is emitted after res.send() Nov 25, 2013 at 12:36
  • @vkurchatkin A bit of both, actually. Note that I wasn't linking to the latest version of the docs as the 'finish' event didn't exist in a stable release before v0.10.0. Before that, both scenarios would emit a 'close' event -- http.ServerResponse (v0.8.26) and Writable Stream (v0.8.26). But, you are right that 'close' is more than just for backwards support and I've edited for it. Nov 25, 2013 at 16:08
  • 4
    Is it necessary to remove the listener? When the response is finish, neither itself nor the listener will be used again, or will they?
    – user659025
    Oct 22, 2016 at 14:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.