diff --git a/index.js b/index.js index 0056649..4178a63 100644 --- a/index.js +++ b/index.js @@ -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 => { @@ -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)) } } diff --git a/test/index.js b/test/index.js index 4a8c3bf..f94fa02 100644 --- a/test/index.js +++ b/test/index.js @@ -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('日本語') + ]) + 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('hello') + const error = t.throws(() => toUTF8(buffer, 'text/html; charset=iso-2022-jp')) + t.true(error.message.includes('iso-2022-jp')) +})