Node.Js / Express is a simple middleware to output the first few characters of a response

For registration / debugging, I would like to output the first hundreds of characters or so of the answer right before sending it to the browser. Is there something simple I can do with middleware and an answer object for this?

Ideally, this is something like:

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

Except that the answer has no body, and I cannot figure out where the current body is being sent, which will be sent back.

UPDATE:

Peter's answer worked, I suppose I would put my middleware code in order to save future viewers with 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(); }); 
+4
source share
1 answer

Thus, you need to connect to the response output API, which is not as simple in middleware as binding to request processing. The best example to view is to link the embedded logger middleware . This is basically a monkey - corrects the req.end method and forwards this data to its stream, and then proceeds to calling the real req.end function. You should follow this pattern, which should work well for non-flow answers.

This template can ultimately provide you with only the last piece of data (for the case of a streaming response). If so, you just need monkey-patch res.write instead of res.end and you will get access to the first fragment. Just un-monkey-patch res.write after you have registered the first fragment.

+5
source

All Articles