From 028b8f0e4bb2f2f799c959d9b9b67c10903b81b6 Mon Sep 17 00:00:00 2001 From: David Frank Date: Wed, 3 Aug 2016 14:03:22 +0800 Subject: [PATCH] skip content encoding detection for non-html/xml/plain text response --- lib/body.js | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/lib/body.js b/lib/body.js index 4c6bb71..4e050ca 100644 --- a/lib/body.js +++ b/lib/body.js @@ -90,12 +90,14 @@ Body.prototype._decode = function() { return new Body.Promise(function(resolve, reject) { var resTimeout; + // body is string if (typeof self.body === 'string') { self._bytes = self.body.length; self._raw = [new Buffer(self.body)]; return resolve(self._convert()); } + // body is buffer if (self.body instanceof Buffer) { self._bytes = self.body.length; self._raw = [self.body]; @@ -115,6 +117,7 @@ Body.prototype._decode = function() { reject(new FetchError('invalid response body at: ' + self.url + ' reason: ' + err.message, 'system', err)); }); + // body is stream self.body.on('data', function(chunk) { if (self._abort || chunk === null) { return; @@ -153,12 +156,18 @@ Body.prototype._convert = function(encoding) { encoding = encoding || 'utf-8'; + var ct = this.headers.get('content-type'); var charset = 'utf-8'; var res, str; // header - if (this.headers.has('content-type')) { - res = /charset=([^;]*)/i.exec(this.headers.get('content-type')); + if (ct) { + // skip encoding detection altogether if not html/xml/plain text + if (!/text\/html|text\/plain|\+xml|\/xml/i.test(ct)) { + return Buffer.concat(this._raw); + } + + res = /charset=([^;]*)/i.exec(ct); } // no charset in content type, peek at response body for at most 1024 bytes