Node/Express middleware to post-process requests

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

//  configure express app

    //  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

                //  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).
                    //  the user agent
                    //  the requested path
                    //  the HTTP status code returned


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

        if (done)


Leave a Reply

Your email address will not be published. Required fields are marked *