Node.jsでの文字コードの変換

node.jsaws

node-iconvを使う。

$ npm install iconv

SHIFT_JISからUTF-8への変換はこんな感じ。

const Iconv  = require('iconv').Iconv;

const before = new Buffer([
    0x8b, 0x8d, 
    0x8e, 0x4d, 
    0x26,
    0x82, 0xb2,
    0x94, 0xd1
]);

const iconv = new Iconv('SHIFT_JIS', 'UTF-8');
console.log(`before: ${before.toString('hex')} ${before.toString()}`)
const after = iconv.convert(before);
console.log(`after:  ${after.toString('hex')} ${after.toString()}`);
before: 8b8d8e4d2682b294d1 ���M&����
after:  e7899be79abf26e38194e9a3af 牛皿&ご飯

文字コードによっては変換後に表せないことがある。 例えば、UTF-8からSHIFT_JISへの変換でサロゲートペア🍚を渡すと変換できず、エラーになる。

throw errnoException('EILSEQ', 'Illegal character sequence.');

//IGNORE付けることで そのような文字があった場合でもエラーにしないようにできる。

const Iconv  = require('iconv').Iconv;

const before = "牛皿&🍚";

const iconv = new Iconv('UTF-8', 'SHIFT_JIS//IGNORE');
console.log(`before: ${new Buffer(before).toString('hex')} ${before.toString()}`)
const conv = iconv.convert(before);
const iconv2 = new Iconv('SHIFT_JIS', 'UTF-8');
const after = iconv2.convert(conv);
console.log(`after:  ${after.toString('hex')} ${after.toString()}`);

変換できないものは無視される。

before: e7899be79abf26f09f8d9a 牛皿&🍚
after:  e7899be79abf26 牛皿&

Lambdaでは

Lambdaではインストールされているiconvコマンドを使うことができる。

return new Promise((resolve, reject) => {
    let filePath = "/tmp/shiftjis";
    fs.writeFileSync(filePath, shiftjis);
    var exec = require('child_process').exec;
    var cmd = `iconv -c -f sjis -t utf-8 ${filePath}`;
    var child = exec(cmd, (err, stdout, stderr) => {
      if (err) reject(err);
      else resolve(stdout);
    });
});

参考

AWS Lambda内で文字コードを変換する方法 - ボクココ