Hello guys I’m trying to create a middleware in express
function logResponseBody(req, res, next) {
var oldWrite = res.write,
oldEnd = res.end;
const maxSize = 1023;
var chunks = [];
res.write = function (chunk) {
chunks.push(new Buffer(chunk));
oldWrite.apply(res, arguments);
};
res.end = function (chunk) {
if (chunk)
chunks.push(new Buffer(chunk));
var body = Buffer.concat(chunks).toString('utf8');
console.log(req.path, body);
if (responseSize > maxSize) {
// here return a status code 314 and a message the response body is to big
}
oldEnd.apply(res, arguments);
};
next();
}
app.use(logResponseBody);
What I’m trying to achive is the check if response body is greater than 1mb then return a custom response with error message.
I have a part of the code but when I try to return the response with res.end it gets stuck in the loop