4

For logging/debugging I'd like to output the first hundred characters or so of the response right before its sent to browser. Is there something simple I can do with middleware and the response object to do this?

Ideally its something like:

app.use(function(req, res, next) {
    console.log('Response snippet: '+((res.body || '').substr(0,100)));
    next();
});

Except the response doesn't have a body and I cannot quite figure out where the current body to be sent back is passed.

UPDATE:

Peter's answer worked, I figure I'd put my middleware code here to save future viewers a click:

App.use(function(req, res, next) {
    var end = res.end;
    res.end = function(chunk, encoding){
        res.end = end;
        if (chunk) {
            console.log(chunk);
        }
        res.end(chunk, encoding);
    };
    next();
});
Aaron Silverman
  • 22,070
  • 21
  • 83
  • 103
  • Do you have app.use(express.bodyParser()) somewhere in your app.js? It should be before your routes are declared as part of you app.configure. – Hector Correa Dec 03 '12 at 19:46
  • Not using bodyParser but added it in. It seems it makes available body for req, but not for res. I want to peak at what I am sending OUT. – Aaron Silverman Dec 03 '12 at 20:15
  • I don;t know if there is support built-in Express for this. I suspect you'd need to look at the response after the res.render() but I don't know if there are any hook for that. – Hector Correa Dec 03 '12 at 20:31
  • you can listen on `res.on('data', callback)` but if you're using `express.compress()` then it would be binary. if this is only for development, you can just not enable compression. – Jonathan Ong Dec 05 '12 at 09:12

1 Answers1

5

So you need to hook into the response output API, which is not as straightforward in middleware as hooking into the request processing. The best example to look at is connect's built-in logger middleware. It basically monkey-patches the req.end method and forwards that data on to its stream, then proceeds to invoke the real req.end function. You need to follow this pattern, which should work fine for non-streaming responses.

That pattern may end up only giving you the last chunk of data (for the case of a streamed response). If so, you need to just monkey-patch res.write instead of res.end and you'll get access to the first chunk. Just un-monkey-patch res.write once you've logged the first chunk.

Nathan
  • 1,762
  • 1
  • 20
  • 30
Peter Lyons
  • 142,938
  • 30
  • 279
  • 274