Created
April 1, 2020 19:14
-
-
Save hashtagchris/e9216737ef10d827e734f1933e9202a7 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
// 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