Created
February 19, 2016 12:54
-
-
Save bokuo-okubo/d2fc1bc80f270bd44117 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
const Iconv = require('iconv').Iconv; | |
const Chardet = require('jschardet'); | |
/** | |
* convertEncode: 生バイト列のエンコードを変換する | |
* @param {Buffer} buf バイト列 | |
* @param {String} decoding 期待する変換後の文字エンコード | |
* @return {Promise(String)} 変換対象文字列を包んだPromise | |
*/ | |
module.exports = function convertEncode(buf, decoding) { | |
decoding = decoding || 'UTF-8//TRANSLIT//IGNORE'; | |
return convert(buf, parseEncode(buf), decoding); | |
} | |
function convert(buf, encoding, decoding) { | |
decoding = decoding || 'UTF-8//TRANSLIT//IGNORE'; | |
return new Promise((resolve, reject) => { | |
try { | |
let iconv = new Iconv(encoding, decoding); | |
resolve(iconv.convert(buf).toString()); | |
} catch(err) { | |
reject(err); | |
} | |
}); | |
} | |
function parseEncode(buf) { | |
return Chardet.detect(buf).encoding; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment