-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdetectAndEncodeResponse.js
64 lines (54 loc) · 1.59 KB
/
detectAndEncodeResponse.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
/**
* Author: Maor Magori
* Heavily inspired by @magicdawn superagent-charset package: https://github.com/magicdawn/superagent-charset
*/
const chardet = require("chardet");
const iconv = require("iconv-lite");
module.exports = function install(superagent) {
const Request = superagent.Request;
/**
* add `charset` to request
*
* @param {String} enc : default encoding
* @param {number} bytesAmountForDetection : amount of bytes needed to estimate encoding
*/
Request.prototype.charset = function (enc, bytesAmountForDetection) {
if (!enc) enc = "UTF-8";
this._parser = function (res, cb) {
let detectedEncoding;
let bytesSummed = 0;
const chunks = [];
res.on("data", function (chunk) {
chunks.push(chunk);
if (!detectedEncoding) {
bytesSummed += chunk.length;
if (
bytesAmountForDetection &&
bytesSummed > bytesAmountForDetection
) {
detectedEncoding = chardet.detect(Buffer.concat(chunks));
}
}
});
res.on("end", function () {
let text, err;
const responseBuffer = Buffer.concat(chunks);
try {
if (!bytesAmountForDetection)
detectedEncoding = chardet.detect(responseBuffer);
if (!detectedEncoding) {
detectedEncoding = enc;
}
text = iconv.decode(responseBuffer, detectedEncoding);
} catch (e) {
err = e;
} finally {
res.text = text;
cb(err);
}
});
};
return this;
};
return superagent;
};