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
7 changes: 5 additions & 2 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,10 @@ const ICONV_ALIASES = {

const inferredEncoding = content => {
const detected = jschardet.detect(content)
return detected && detected.encoding
const encoding = detected && toIconvName(detected.encoding)
// jschardet 4 can name codecs iconv-lite does not ship (ISO-2022-JP, cp500, …).
// Skip those so the caller falls back to the target encoding instead of throwing.
if (encoding && iconv.encodingExists(encoding)) return encoding
}

const toIconvName = encoding => {
Expand All @@ -27,7 +30,7 @@ module.exports = targetEncoding => {

const getEncoding = (content, contentType) =>
toIconvName(charset({ 'content-type': contentType }, content)) ||
toIconvName(inferredEncoding(content)) ||
inferredEncoding(content) ||
targetEncoding

return (buffer, contentType) => {
Expand Down
22 changes: 22 additions & 0 deletions test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -47,3 +47,25 @@ test('throws when the declared charset is unknown to iconv', t => {
const error = t.throws(() => toUTF8(buffer, 'text/html; charset=iso-2022-jp'))
t.true(error.message.includes('iso-2022-jp'))
})

test('falls back when inferred encoding is unknown to iconv', t => {
// ISO-2022-JP ESC sequences: jschardet is confident; iconv-lite has no codec.
const buffer = Buffer.concat([
Buffer.from('<html><body>'),
Buffer.from([0x1b, 0x24, 0x42, 0x46, 0x7c, 0x4b, 0x5c, 0x38, 0x6c, 0x1b, 0x28, 0x42]),
Buffer.from('</body></html>')
])
const output = toUTF8(buffer, 'text/html')
t.true(output.includes('<html>'))
t.true(output.includes('</html>'))
})

test('falls back when jschardet guesses an unsupported encoding', t => {
const iconv = require('iconv-lite')
const buffer = iconv.encode(
'<html><body>' + 'あ'.repeat(200) + '</body></html>',
'EUC-JP'
)
const output = toUTF8(buffer, 'text/html')
t.true(output.includes('<html>'))
})
Loading