Skip to content

Instantly share code, notes, and snippets.

@bitdivine
Created November 10, 2015 16:01
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bitdivine/42cc3ce6c1dad50ccbe0 to your computer and use it in GitHub Desktop.
Save bitdivine/42cc3ce6c1dad50ccbe0 to your computer and use it in GitHub Desktop.
module.exports = request_promise_compressed;
var request = require('request-promise')
, bb = require('bluebird')
, zlib = require('zlib');
function request_promise_compressed(url){ // Supports compressed=true;
if (!url.compressed) return request(url);
var resolveWithFullResponse = url.resolveWithFullResponse;
var encoding = url.encoding;
url.headers = url.headers || {};
url.headers["Accept-Encoding"] = url.headers["Accept-Encoding"] || "gzip,deflate";
url.resolveWithFullResponse = true;
url.encoding = null;
return request(url).then(function(res){
// Body:
var body = (function(){
switch(res.headers && res.headers['content-encoding']){
case 'deflate' : return bb.promisify(zlib.deflate)(res.body);
case 'gzip' : return bb.promisify(zlib.gunzip)(res.body);
default : return res.body;
}
})().then(function(buffer){return buffer.toString(encoding);});
if (resolveWithFullResponse){
return body.then(function(b){res.body = b; return res;});
} else {
return body;
}
});
}
@kryogenic
Copy link

I found that I had to make a clone of the url object in order for this function to work properly:
url = require('util')._extend({}, url)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment