Skip to content

Instantly share code, notes, and snippets.

@ianmstew
Last active August 29, 2015 14:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ianmstew/d934816689fb19d65e66 to your computer and use it in GitHub Desktop.
Save ianmstew/d934816689fb19d65e66 to your computer and use it in GitHub Desktop.
nodejs http patcher
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