0

I have 2 strings. Would like it all to first make a .txt file and then save the strings to it as unicode.

function WriteFile(file, str, str2)
{
    var tmp=real_url.replace(/%20/g, " ");

    var WshNetwork=new ActiveXObject("WScript.Network");
    var userid=WshNetwork.UserName;

    var fso = new ActiveXObject("Scripting.FileSystemObject");

    if(! fso.FolderExists(tmp+"users/"+userid))
    {
        var cf = fso.CreateFolder(tmp+"users/"+userid);
    }
    else
    {
        //alert("THIS FOLDER ALREADY EXISTS");
    }

    delete fso;

    var fso = new ActiveXObject("Scripting.FileSystemObject");

    var fh = fso.OpenTextFile(tmp+"users/"+userid+"/"+file, 2, true);
    fh.WriteLine(str);
    fh.WriteLine(str2);

    fh.Close();
    delete fso;

    return;
}

I

Cheran Shunmugavel
  • 8,319
  • 1
  • 33
  • 40
basickarl
  • 37,187
  • 64
  • 214
  • 335
  • You can't read/write to a file in Client-Side JavaScript from exterior site. This is a violation of safety policy. – freakish Jan 10 '12 at 12:03
  • 1
    It is not browser-based Javascript, it is Windows Scripting Host code, which can use APIs to access the local filesystem. – Philippe Plantier Jan 10 '12 at 12:06
  • By the way, this is not really a duplicate, but the answers to this question may solve your problem: http://stackoverflow.com/questions/2840252/writing-utf8-text-to-file – Philippe Plantier Jan 10 '12 at 13:03
  • 2
    found the solution! its in the attributs of writeLine. you have to declare -1. – basickarl Jan 10 '12 at 15:07
  • Karl, you should repost your solution and mark it as answered. You are correct, the WriteLine method accepts an optional third parameter in the form of a tristate value that indicates whether a file should be opened as Unicode, Ansi, or the system default. Also, there is no need to recreate the FileSystemObject in your code. You can reuse your variable. Otherwise you are just adding unnecessary overhead to your script. – Nilpo Jan 11 '12 at 19:11
  • The Write* methods do not allow you to specify the encoding (That would mean you could change the encoding in the middle of a file) Only the Open/Create methods allow you to specify the encoding... – Anders Jan 12 '12 at 03:30

1 Answers1

2

Both the CreateTextFile and OpenTextFile methods have a parameter that specify the encoding (ASCII or Unicode (UTF16LE))

var fso = new ActiveXObject("Scripting.FileSystemObject");
var filename = "c:\\testfile.txt";
var f = fso.OpenTextFile(filename, 2, true, -1); // -1 means unicode
f.WriteLine("Hello world!");
f.Close();
Anders
  • 97,548
  • 12
  • 110
  • 164