diff --git a/index.js b/index.js index 4178a63..b7ede2e 100644 --- a/index.js +++ b/index.js @@ -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 => { @@ -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) => { diff --git a/test/index.js b/test/index.js index f94fa02..518c404 100644 --- a/test/index.js +++ b/test/index.js @@ -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(''), + Buffer.from([0x1b, 0x24, 0x42, 0x46, 0x7c, 0x4b, 0x5c, 0x38, 0x6c, 0x1b, 0x28, 0x42]), + Buffer.from('') + ]) + const output = toUTF8(buffer, 'text/html') + t.true(output.includes('')) + t.true(output.includes('')) +}) + +test('falls back when jschardet guesses an unsupported encoding', t => { + const iconv = require('iconv-lite') + const buffer = iconv.encode( + '' + 'あ'.repeat(200) + '', + 'EUC-JP' + ) + const output = toUTF8(buffer, 'text/html') + t.true(output.includes('')) +})