Skip to content

Instantly share code, notes, and snippets.

@hashtagchris
Created April 1, 2020 19:14
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 hashtagchris/e9216737ef10d827e734f1933e9202a7 to your computer and use it in GitHub Desktop.
Save hashtagchris/e9216737ef10d827e734f1933e9202a7 to your computer and use it in GitHub Desktop.
// Example usage: node gunzip_http_response.js http://www.httpbin.org/gzip
const http = require('http');
const zlib = require('zlib');
const url = process.argv[2];
console.log(`Requesting ${url}...`);
const req = http.request(url);
req.on('response', function(incomingMessage) {
console.log(`STATUS: ${incomingMessage.statusCode}`);
console.log(`HEADERS: ${JSON.stringify(incomingMessage.headers)}`);
let responseBody = Buffer.alloc(0);
// If you set the encoding, you'll get string chunks instead of buffer chunks
// incomingMessage.setEncoding('utf8');
incomingMessage.on('data', function (chunk) {
if (typeof(chunk) === 'string') {
console.error("WARNING: Processing a string instead of a buffer. YUCK!");
}
responseBody = Buffer.concat([responseBody, chunk]);
});
incomingMessage.on('end', function () {
console.log();
const destination = process.stdout;
if (incomingMessage.headers['content-encoding'] === 'gzip') {
console.log('gunzipping response...');
console.log();
const gunzip = zlib.createGunzip();
gunzip.pipe(destination);
gunzip.write(responseBody);
}
else {
console.log();
destination.write(responseBody);
}
});
});
req.on('error', (e) => {
console.error(`problem with request: ${e.message}`);
});
req.end();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment