Help us understand the problem. What is going on with this article?

Node.jsで文字コードの自動判別と自動変換

More than 5 years have passed since last update.
  • 文字コードの自動判別 - jschardet
  • 文字コードの変換 - iconv

流れとしてはjschardetを使って文字コードを自動判別し、その文字コードからiconvを使ってUTF-8に変換します。

shoma2daをフォロー

まずはモジュールのインストール。

$ npm install jschardet --save
$ npm install iconv --save

文字コード判定をしてみます。

//test.jsに書きました
var jschardet = require('jschardet');

var notUtf8String = /* どこかから持ってきたUTF-8じゃなさそうな文字列 */;

var detectResult = jschardet.detect(notUtf8String);
console.log(detectResult);

実行してみます。

$ node test.js
{ encoding: 'ISO-8859-2', confidence: 0.7299161297501421 }

今回の例ではISO-8859-2っぽいよ!というのが出ました。

続いて変換です。
iconvを使えばこちらもシンプルにできます。

var Iconv = require('iconv').Iconv;
var iconv = new Iconv('ISO-8859-2', 'UTF-8//TRANSLIT//IGNORE');
var convertedString = iconv.convert(notUtf8String).toString();

合わせて書くと

var jschardet = require('jschardet');
var Iconv = require('iconv').Iconv;

var notUtf8String = /* どこかから持ってきたUTF-8じゃなさそうな文字列 */;

//文字コード判定
var detectResult = jschardet.detect(notUtf8String);

//判定した文字コードからUTF-8に変換
var iconv = new Iconv(detectResult.encoding,'UTF-8//TRANSLIT//IGNORE');
var convertedString = iconv.convert(notUtf8String).toString();

shoma2daをフォロー

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした