How to read and write a file using javascript?
Files can be read and written by using java script functions β fopen(),fread() and fwrite().
The function fopen() takes two parameters β 1. Path and 2. Mode (0 for reading and 3 for writing). The fopen() function returns -1, if the file is successfully opened.
Example:
file=fopen(getScriptPath(),0);
The function fread() is used for reading the file content.
Example:
str = fread(file,flength(file) ;
The function fwrite() is used to write the contents to the file.
Example:
file = fopen("c:\MyFile.txt", 3);// opens the file for writing
fwrite(file, str);// str is the content that is to be written into the file.
How to read and write a file using javascript?
There are two ways to do it:
1. Using JavaScript extensions (runs from JavaScript Editor), or
2. Using a web page and ActiveX objects (Internet Explorer only)
In JavaScript Extensions, you can use
fh = fopen(getScriptPath(), 0); to open a file
Using ActiveX objects, following should be included in your code to read a file:
var fso = new ActiveXObject("Scripting.FileSystemObject");
var s = fso.OpenTextFile("C:\\example.txt", 1, true);