JavaScript read and write files
<script>
/*
Object. OpenTextFile (filename[, iomode[, create[, format]])
Parameters
Object
Required option. Object should be the name of the FileSystemObject.
FileName
Required option. A string expression that indicates the file you want to open.
IOMode
Options available. Can be one of three constants: ForReading, ForWriting, or forappending.
Create
Options available. Boolean value that indicates whether to create a new file when the specified filename does not exist. True If a new file is created, False if it is not created. If omitted, the new file is not created.
Format
Options available. Use one of the three-state values to indicate the format of the open file. If omitted, the file is opened in ASCII format.
Set up
The IOMode parameter can be any of the following settings:
Constant numerical description
ForReading 1 Opens the file as read-only. Can't write this file.
ForWriting 2 Open File as Write
ForAppending 8 Opens the file and begins writing at the end of the file.
The format parameter can be any of the following settings:
Value Description
TristateTrue opens the file in Unicode format.
Tristatefalse opens the file in ASCII format.
Tristateusedefault to open the file using the system default value.
*/
Read files
function readFile (filename) {
var fso = new ActiveXObject ("Scripting.FileSystemObject");
var f = fso. OpenTextFile (filename,1);
var s = "";
while (!f.atendofstream)
S + + f.readline () + "\ n";
F.close ();
return s;
}
Write a file
function WriteFile (filename,filecontent) {
var fso, F, S;
FSO = new ActiveXObject ("Scripting.FileSystemObject");
f = fso. OpenTextFile (filename,8,true);
F.writeline (filecontent);
F.close ();
Alert (' OK ');
}
</script>
<input type= "text" id= "in" name= "in"/>
<input type= "button" value= "write!" onclick= "WriteFile (' C:/12.txt ', document.getElementById (' in '). Value);" /><br><br>
<input type= "button" value= "read!" onclick= "document.getElementById (' Show '). Value=readfile (' c:/12.txt ');" /><br>
<textarea id= "Show" Name= "Show" cols= "rows=" 8 ">
</textarea>