Skip to content

Instantly share code, notes, and snippets.

@parvezmrobin
Last active September 18, 2020 15:08
Show Gist options
  • Save parvezmrobin/2723626791804890ea34804cf0bd5eb7 to your computer and use it in GitHub Desktop.
Save parvezmrobin/2723626791804890ea34804cf0bd5eb7 to your computer and use it in GitHub Desktop.
Intercept / Log anything you write to your express response from anywhere from any file. Just add the following code to your `app.js`.
app.use((request, response, next) => {
// wheather `req.write` / `req.send` / `req.json`, express calls underlying `socket.write`
// thus intercepting `socket.write`
const backup = response.socket.write;
let code;
function newWriter(...args) {
for (const arg of args) {
if (typeof arg === 'string') {
if (arg.startsWith('HTTP')) { // this means express is writing the HTTP headers
const header = arg.substring(0, arg.indexOf('\n'));
[, code] = header.split(' ');
code = Number.parseInt(code, 10);
}
} else if (arg instanceof Buffer) { // this means something is being written by you
const message = `Responding ${code} | ${arg}`;
if (code < 400) {
console.info(message);
} else if (code < 500) {
console.warn(message);
} else {
console.error(message);
}
}
}
// this line is IMPORTANT. call the actual `socket.write` as well.
return backup.apply(this, args);
}
response.socket.write = newWriter;
next();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment