Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing UTF8 text to file

I am using the following function to save text to a file (on IE-8 w/ActiveX).

function saveFile(strFullPath, strContent)
{
    var fso = new ActiveXObject( "Scripting.FileSystemObject" );

    var flOutput = fso.CreateTextFile( strFullPath, true ); //true for overwrite
    flOutput.Write( strContent );
    flOutput.Close();
}

The code works fine if the text is fully Latin-9 but when the text contains even a single UTF-8 encoded character, the write fails.

The ActiveX FileSystemObject does not support UTF-8, it seems. I tried UTF-16 encoding the text first but the result was garbled. What is a workaround?

like image 415
sonofdelphi Avatar asked May 15 '10 13:05

sonofdelphi


1 Answers

Try this:

function saveFile(strFullPath, strContent) {
 var fso = new ActiveXObject("Scripting.FileSystemObject");
 var utf8Enc = new ActiveXObject("Utf8Lib.Utf8Enc");
 var flOutput = fso.CreateTextFile(strFullPath, true); //true for overwrite
 flOutput.BinaryWrite(utf8Enc.UnicodeToUtf8(strContent));
 flOutput.Close();
}
like image 168
Mathias Bynens Avatar answered Sep 23 '22 03:09

Mathias Bynens