Last Updated: January 28, 2019
·
4.959K
· foozle

Node/Express middleware to post-process requests

//  set up express
var express = require('express'),
    app = express();


//  configure express app
app.configure(function(){

    //  register the 'after response' middleware
    app.use(function(request, response, done){

        //  define our postProcessor
        //  we do this here as we automatically get to access the 
        //  request and response arguments
        function postProcess()
        {
            //  remove the event listeners, ensuring postProcess
            //  only gets called once
            response.removeListener('finish', postProcess);
            response.removeListener('close', postProcess);

            //  always make this as asynchronous as possible
            process.nectTick(function(){

                //  we still have access to the request and response 
                //  variables provided when the our middleware is 
                //  called (we registered registered the function with 
                //  request, response and done arguments).
                console.log(
                    //  the user agent
                    request.headers['user-agent'],
                    //  the requested path
                    request.path,
                    //  the HTTP status code returned
                    response.statusCode
                );

            });
        }

        //  listen for the finish and close events, pass those on to 
        //  the postProcess method
        response.on('finish', postProcess);
        response.on('close', postProcess);


        if (done)
            done();
    });

});