Skip to content
This repository has been archived by the owner on May 1, 2022. It is now read-only.

Commit

Permalink
Fixed gzip/deflate as reported in #1
Browse files Browse the repository at this point in the history
  • Loading branch information
Roel van Uden committed Dec 13, 2014
1 parent dc2819d commit 6450809
Showing 1 changed file with 27 additions and 11 deletions.
38 changes: 27 additions & 11 deletions lib/nodejs/request.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,21 @@ module.exports = function(resource, encoding, done) {
populate(resource, encoding, done);
};

/**
* Creates a callback for a decoded request.
* @param {string} address
* @param {string} encoding
* @param {function(Error, string=)}done
*/
function createRequestCallback(address, encoding, done) {
return function (err, buffer) {
if (err) return done(err);
var data = buffer.toString(encoding || 'utf8');
if (!data) return done(new Error('No data: ' + address));
done(err, data);
};
}

/**
* Retrieves the keys containing a function.
* @private
Expand Down Expand Up @@ -61,20 +76,21 @@ function request(address, encoding, done, n) {
var options = url.parse(address);
options.headers = {'User-Agent': agent};
http.get(options, function(res) {
var data = '';
var resEncoding = res.headers['content-encoding'];
res.setEncoding(encoding || 'utf8');
if (resEncoding === 'gzip') {
res.pipe(zlib.createGunzip());
} else if (resEncoding === 'deflate') {
res.pipe(zlib.createInflate());
}
var chunks = [];
res.on('data', function(chunk) {
data += chunk;
chunks.push(chunk);
});
res.on('end', function() {
if (!data) return done(new Error('No data: ' + address));
done(undefined, data);
var buffer = Buffer.concat(chunks);
var compression = res.headers['content-encoding'];
var callback = createRequestCallback(address, encoding, done);
if (compression == 'gzip') {
return zlib.gunzip(buffer, callback);
} else if (compression === 'deflate') {
return zlib.inflateRaw(buffer, callback);
} else {
callback(undefined, buffer);
}
});
}).on('error', function(err) {
if (n < maximum) return request(address, encoding, done, n + 1 || 1);
Expand Down

0 comments on commit 6450809

Please sign in to comment.