Sunday, November 04, 2007

How to read / write files using JavaScript

To read and write files from JavaScript, we will use an ActiveX Object from the Scripting.FileSystemObject library, which knows how to handle files. The second parameter of the OpenTextFile function represents what we want the object to do with the file (read = 1, write = 2, append = 8).

And here are the scripts:

1. Reading from file

function ReadFromFile(sText){
var fso = new ActiveXObject("Scripting.FileSystemObject");
var s = fso.OpenTextFile("C:\\example.txt", 1, true);
row = s.ReadLine(); //also we can use s.ReadAll() to read all the lines;
alert(row);
s.Close();
}


2. Writing to file

function WriteToFile(sText){
var fso = new ActiveXObject("Scripting.FileSystemObject");
var s = fso.OpenTextFile("C:\\example.txt", 8, true); //if we use 2 instead of 8, the file will be overwritten;
s.WriteLine("new line added");
s.Close();
}


Though, to make this scripts work in Internet Explorer, you must go to Tools/Internet Options/Security, add your page to Trusted sites, then go to Custom level... and look for Initialize and script ActiveX controls not marked as safe for scripting. Enable it and restart the Internet Explorer.

4 comentarii:

Anonymous said...

Very helpful. Is there a way for JS to read write a file locally and not using ActiveX?

Archana said...

Thankyou so much. I was looking for it and could not get the exact code.

Saravanan said...

Thanks a lot. Could you please tell how to read a url file. for example http://localhost/outbound/file.htm.

CSCorpion said...

Saravanan, please check our post http://crmstuff.blogspot.com/2008/10/javascript-code-reuse-in-crm.html . It tells you how to "include" certain *.js files to your work (these files can be internal or external, for example http://yourwebsite/scripts/example.js). You may load your external script with the method proposed in the post above. Hope this helps.

Regards,
CSC