JScript で BOM なし utf-8 ファイルを出力
Scripting.FileSystemObject
だと utf-8
は扱えなくて、ADODB.Stream
というのを使うようです。また、utf-8 を BOM なしにするには
- 一旦 utf-8(BOM付き) でテキストを書き出して
- バイナリで頭から 3byte 目移行を取り出して
- バイナリで書き込む
と。
んでコードなんですが参考リンクとほぼ同じです。new ActiveXObject("ADODB.Stream")
がひとつ減らせてますがこんなのどーでもいいです。備忘。備忘。
function writeUTF8(filename, text) { try { var stream = new ActiveXObject("ADODB.Stream"); //write text to stream as UTF-8. stream.Type = 2; // as TEXT. stream.Charset = "UTF-8"; stream.Open(); stream.WriteText(text); //set position at 0 to change type(error occurs). stream.Position = 0; stream.Type = 1; // as BINARY. //skip bom and read all bytes. stream.Position = 3; var bytes = stream.Read(); //reset stream and write bytes. stream.Position = 0; stream.SetEOS(); stream.Write(bytes); //save. stream.SaveToFile(filename, 2); } finally { if (stream) try { stream.Close(); } catch(e) {} } }
参考:
ADODB.Streamオブジェクトを使ってBOMなしUTF-8のファイルを作成する方法 - 大人になったら肺呼吸
JavaScriptでファイルの書き込みをUTF-8で行う(htaまたは、wsh用) - jiroの日記
ドキュメントはこちらにありました。