Created
November 10, 2015 16:01
-
-
Save bitdivine/42cc3ce6c1dad50ccbe0 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
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; | |
} | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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)