Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read and write text file in JavaScript

How can I write and read a text file with JavaScript?

like image 384
tibin mathew Avatar asked Jul 11 '26 00:07

tibin mathew


2 Answers

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.

like image 59
Quentin Avatar answered Jul 13 '26 14:07

Quentin


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 :)

like image 26
sumit_programmer Avatar answered Jul 13 '26 13:07

sumit_programmer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!