-
Notifications
You must be signed in to change notification settings - Fork 12
/
index.js
89 lines (71 loc) · 1.81 KB
/
index.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
'use strict'
/**
* Module dependencies
*/
const iconv = require('iconv-lite')
/**
* util
*/
const checkEncoding = enc => {
// check iconv supported encoding
if (enc && !iconv.encodingExists(enc)) {
return new Error('encoding not supported by iconv-lite')
}
}
/**
* install the charset()
*/
module.exports = function install(superagent) {
const Request = superagent.Request
/**
* add `charset` to request
*
* @param {String} enc : the encoding
*/
Request.prototype.charset = function(enc) {
if (enc) {
let err = checkEncoding(enc)
if (err) throw err
}
// set the parser
this._parser = function(res, cb) { // res not instanceof http.IncomingMessage
const chunks = []
res.on('data', function(chunk) {
chunks.push(chunk)
})
res.on('end', function() {
let text, err
const buf = Buffer.concat(chunks)
// detect if encoding if not specified
if (!enc) {
if (res.headers['content-type']) {
// Extracted from headers
enc = (res.headers['content-type'].match(/charset=(.+)/) || []).pop()
}
if (!enc) {
// Extracted from <meta charset="gb2312"> or <meta http-equiv=Content-Type content="text/html;charset=gb2312">
enc = (buf.toString().match(/<meta.+?charset=['"]?([^"']+)/i) || []).pop()
}
// check
err = checkEncoding(enc)
if (err) return cb(err)
if (!enc) {
// Default utf8
enc = 'utf-8'
}
}
try {
text = iconv.decode(buf, enc)
} catch (e) {
/* istanbul ignore next */
err = e
} finally {
res.text = text
cb(err)
}
})
}
return this
}
return superagent
}