Last active
August 29, 2015 14:16
-
-
Save ianmstew/d934816689fb19d65e66 to your computer and use it in GitHub Desktop.
nodejs http patcher
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
var httpPatcher = function (http) { | |
// Patch http request() method to capture request | |
var originalRequestFn = http.request; | |
http.request = function (options, requestCb) { | |
console.log('>>> HTTP request >>>\n ' + options.method + ' ' + | |
(options.port === 443 ? 'https' : 'http') + '://' + options.host + options.path); | |
// Patch http request() callback to capture response | |
var originalRequestCb = requestCb; | |
requestCb = function (res) { | |
var responseBodyBuffer = []; | |
res.on('data', function(chunk) { | |
responseBodyBuffer[responseBodyBuffer.length] = chunk; | |
}); | |
res.on('end', function() { | |
console.log('>>> HTTP response >>>\n ', responseBodyBuffer.join('')); | |
}); | |
return originalRequestCb.apply(this, arguments); | |
}; | |
// Make the request | |
var req = originalRequestFn.call(http, options, requestCb); | |
// Patch request write() method to capture request body | |
var originalWriteFn = req.write; | |
req.write = function (data) { | |
// Pretty-print URL-encoded body | |
if (options.headers | |
&& options.headers['Content-Type'] | |
&& options.headers['Content-Type'] === 'application/x-www-form-urlencoded') { | |
console.log('>>> HTTP request body >>>\n ', | |
decodeURIComponent(data).replace(/&/g, '\n ')); | |
} | |
// String dump other body encodings | |
else { | |
console.log('>>> HTTP request body >>>\n ', data); | |
} | |
return originalWriteFn.apply(this, arguments); | |
}; | |
return req; | |
}; | |
}; | |
http = require('http'); | |
https = require('https'); | |
httpPatcher(http); | |
httpPatcher(https); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment