Skip to content

Instantly share code, notes, and snippets.

@cakesmith
Created February 25, 2021 23:11
Show Gist options
  • Save cakesmith/4e08930d8a84250be939d434824e1cf6 to your computer and use it in GitHub Desktop.
Save cakesmith/4e08930d8a84250be939d434824e1cf6 to your computer and use it in GitHub Desktop.
//hijack.js
const http = require("http")
function hijack() {
override(http)
}
function requestLogger(req) {
const log = {
method: req.method || "GET",
host: req.host || req.hostname || "localhost",
port: req.port || "443",
path: req.pathname || req.path || "/",
headers: req.headers || {},
}
console.log('Request:');
console.log(log);
}
function responseLogger(response, body) {
const log = {
statusCode: response.statusCode,
headers: response.headers,
message: response.statusMessage,
body
};
console.log('Response:')
console.log(log);
}
function override(module) {
const original = module.request
function wrapper(outgoing) {
const req = original.apply(this, arguments);
const emit = req.emit;
let body = '';
req.emit = function (eventName, response) {
switch (eventName) {
case 'response': {
response.on('data', d => {
body += d;
});
response.on('end', () => {
responseLogger(response, body);
});
}
}
return emit.apply(this, arguments);
}
requestLogger(outgoing);
return req
}
module.request = wrapper
}
module.exports = hijack;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment