Created
February 25, 2021 23:11
-
-
Save cakesmith/4e08930d8a84250be939d434824e1cf6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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