Skip to content

Instantly share code, notes, and snippets.

@bokuo-okubo
Created February 19, 2016 12:54
Show Gist options
  • Save bokuo-okubo/d2fc1bc80f270bd44117 to your computer and use it in GitHub Desktop.
Save bokuo-okubo/d2fc1bc80f270bd44117 to your computer and use it in GitHub Desktop.
'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