LoginSignup
3
1

More than 5 years have passed since last update.

node.jsでUnicodeテキストだけをエスケープする

Posted at

はじめに

TinyMCEの本体やプラグインなどでは、言語リソースファイルは Unicode 文字がエスケープされて書かれていますが、

ja.ls
tinymce.addI18n('ja',{
        moxiemanager_insert:"\u30D5\u30A1\u30A4\u30EB\u306E\u633F\u5165"
});

素の UTF-8 のテキストをこんな感じに変換してくれる方法がちょっと検索しても見つけられなかったので書いてみました。java で言う native2ascii みたいなものです。

使い方

こんな感じです。出力ファイル名は省略可能で、その時は標準出力に書き出します。
bash
% node escapeUnicode.js [入力ファイル] [出力ファイル(省略可)]

ソースコード

escapeUnicode.js
var argc = process.argv.length;

if (argc != 3 && argc != 4) {
    console.log("node escapeUnicode.js [nameFileRead] [nameFileWrite]");
    return;
}

var nameFileRead = process.argv[2];
var nameFileWrite = process.argv[3];

var fs = require("fs");

var text = null;
try {
    text = fs.readFileSync(nameFileRead, "utf8");
} catch (e) {
    console.log("fs.readFileSync(): Caught exception: " + e);
    return;
}

text = text.replace(/[\u0080-\uffff]+/g, function (match) {
    return escape(match).replace(/%u/g, "\\u");
});

if (nameFileWrite == undefined || nameFileWrite == "-") {
    console.log(text);
    return;
}

try {
    fs.writeFileSync(nameFileWrite, text, "utf8");
} catch (e) {
    console.log("fs.writeFileSync(): Caught exception: " + e);
    return;
}

console.log("Wrote to " + nameFileWrite);

「それ…でできるよ」

ツッコミ頂けると嬉しいです。
経験的にもこういうのは投稿した直後に既存の(しかももっと良い)方法が見つかることが多かったので敢えて投稿してみました(苦笑)

3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1