-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
28 lines (23 loc) · 826 Bytes
/
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
'use strict'
const jschardet = require('jschardet')
const isBuffer = require('is-buffer')
const iconv = require('iconv-lite')
const charset = require('charset')
const inferredEncoding = content => {
const charset = jschardet.detect(content)
return charset && charset.encoding
}
module.exports = targetEncoding => {
if (!iconv.encodingExists(targetEncoding)) {
throw new TypeError(`Target encoding '${targetEncoding}' not supported.`)
}
const getEncoding = (content, contentType) =>
charset({ 'content-type': contentType }, content) ||
inferredEncoding(content) ||
targetEncoding
return (buffer, contentType) => {
if (!isBuffer(buffer)) throw new TypeError('content should be a buffer.')
const encoding = getEncoding(buffer, contentType)
return iconv.decode(buffer, encoding)
}
}