diff --git a/index.js b/index.js index adb28a2..c7b99b3 100644 --- a/index.js +++ b/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); }; diff --git a/readme.md b/readme.md index 2d658c5..7e60437 100644 --- a/readme.md +++ b/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 diff --git a/test.js b/test.js index d4a89d8..545628a 100644 --- a/test.js +++ b/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(); + }); +});