How can I write and read a text file with JavaScript?
You need to run the JS in a host environment that provides an API for accessing the file system.
If you are on Windows, then you can use WSH to achieve this.
JS running a browser, under normal security conditions, cannot access the file system.
If you are using Firefox, this may help.
//Your text file location on system
var savefile = "c:\\yourtextfile.txt";
try {
netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
var file = Components.classes["@mozilla.org/file/local;1"]
.createInstance(Components.interfaces.nsILocalFile);
file.initWithPath( savefile );
if ( file.exists() == false ) {
alert( "Creating file... " );
file.create( Components.interfaces.nsIFile.NORMAL_FILE_TYPE, 420 );
}
var outputStream = Components.classes["@mozilla.org/network/file-output-stream;1"]
.createInstance( Components.interfaces.nsIFileOutputStream );
outputStream.init( file, 0x04 | 0x08 | 0x20, 420, 0 );
var output = "Your text here";
var result = outputStream.write( output, output.length );
outputStream.close();
alert("Done");
}
catch (e) {
alert("Some error occured");
}
It worked for me, hope works for you as well :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With