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 comments

Leave a comment

Your email address will not be published. Required fields are marked *