Browse Source

Merge pull request #5 from julien-f/encoding

Encoding support (fix #4).
http2
Sindre Sorhus 10 years ago
parent
commit
68c91676eb
  1. 31
      index.js
  2. 6
      readme.md
  3. 8
      test.js

31
index.js

@ -8,6 +8,10 @@ var assign = require('object-assign');
module.exports = function (url, opts, cb) {
var redirectCount = 0;
// Extract got options.
var encoding = opts.encoding;
delete opts.encoding;
var get = function (url, opts, cb) {
if (typeof opts === 'function') {
cb = opts;
@ -27,8 +31,6 @@ module.exports = function (url, opts, cb) {
var arg = assign({}, parsedUrl, opts);
fn.get(arg, function (res) {
var ret = '';
// redirect
if (res.statusCode < 400 && res.statusCode >= 300 && res.headers.location) {
res.destroy();
@ -54,16 +56,29 @@ module.exports = function (url, opts, cb) {
res = unzip;
}
res.setEncoding('utf8');
res.once('error', cb);
res.on('data', function (data) {
ret += data;
});
var chunks = [];
var n = 0;
res.once('error', cb);
res.on('data', function (chunk) {
// Add the new chunk to the list.
chunks.push(chunk);
n += chunk.length;
});
res.once('end', function () {
cb(null, ret, res);
// Concatenate all chunks into a single buffer.
var data = Buffer.concat(chunks, n);
// Unless the encoding has been explicitely set to `null`,
// convert the buffer to a string.
if (encoding !== null) {
data = data.toString(encoding || 'utf8');
}
// Return the result.
cb(null, data, res);
});
}).once('error', cb);
};

6
readme.md

@ -47,6 +47,12 @@ Type: `object`
Any of the [`http.request`](http://nodejs.org/api/http.html#http_http_request_options_callback) options.
##### options.encoding
Type: `string` or `null`
Encoding to be used on setEncoding of response data. If null, the body is returned as a Buffer.
##### callback(err, data, response)
###### data

8
test.js

@ -58,3 +58,11 @@ it('should support gzip', function (done) {
done();
});
});
it('should return a buffer if encoding is set to null', function (done) {
got('http://google.com', {encoding: null}, function (err, data) {
assert(!err, err);
assert.ok(Buffer.isBuffer(data));
done();
});
});

Loading…
Cancel
Save