Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 15 additions & 6 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,19 @@ const isBuffer = require('is-buffer')
const iconv = require('iconv-lite')
const charset = require('charset')

// jschardet 4 names UTF-8 with a BOM `UTF-8-SIG`. That is UTF-8; iconv-lite has no such codec.
const ICONV_ALIASES = {
'utf-8-sig': 'utf-8'
}

const inferredEncoding = content => {
const charset = jschardet.detect(content)
return charset && charset.encoding
const detected = jschardet.detect(content)
return detected && detected.encoding
}

const toIconvName = encoding => {
if (!encoding) return encoding
return ICONV_ALIASES[encoding.toLowerCase()] || encoding
}

module.exports = targetEncoding => {
Expand All @@ -16,13 +26,12 @@ module.exports = targetEncoding => {
}

const getEncoding = (content, contentType) =>
charset({ 'content-type': contentType }, content) ||
inferredEncoding(content) ||
toIconvName(charset({ 'content-type': contentType }, content)) ||
toIconvName(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)
return iconv.decode(buffer, getEncoding(buffer, contentType))
}
}
16 changes: 16 additions & 0 deletions test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,3 +31,19 @@ test('inferred', t => {
const output = toUTF8(buffer, 'text/html')
t.true(output.includes('次常用國字標準字體表'))
})

test('UTF-8 with BOM and no charset hint', t => {
const buffer = Buffer.concat([
Buffer.from([0xef, 0xbb, 0xbf]),
Buffer.from('<html><body>日本語</body></html>')
])
const output = toUTF8(buffer, 'text/html')
t.true(output.includes('日本語'))
t.false(output.startsWith('\uFEFF'))
})

test('throws when the declared charset is unknown to iconv', t => {
const buffer = Buffer.from('<html>hello</html>')
const error = t.throws(() => toUTF8(buffer, 'text/html; charset=iso-2022-jp'))
t.true(error.message.includes('iso-2022-jp'))
})
Loading