Node.Js/ Express - simple middleware to output fir

2019-05-04 09:31发布

问题:

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();
});

回答1:

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.