Javascript writes TXT and reads TXT file examples

  • 2020-03-30 01:43:12
  • OfStack

1. Write

FileSystemObject translates files into a file stream.

The first step:

Ex. :
 
Var fso=new ActiveXObject(Scripting.FileSystemObject); 

Create an object that translates a file into a file stream.

Step 2: create a textStream object

There are three properties in parentheses

1. The absolute path to the file

2. File constant read only =1, only write =2, add =8 permissions. (ForReading, ForWriting, or ForAppending.) ;

3. If a Boolean value is allowed to be created, it is true; otherwise, it is false;

Ex. :
 
Var f=fso.createtextfile( " C:a.txt " ,2,true); 

Step 3: call the textStream method

1. Write (do not add a new line at the end of the Write)

2. WriteLine (to add a new line break at the end)

3. WriteBlankLines (adds one or more blank lines)

Ex. :
 
f.writeLine( " wo shi di yi hang " ); 

Step 4:

Close the textStream object:

Example: f. lose ();

2. Read

The first step:
The same code at the page code block index 0
Create an object that translates a file into a file stream.

Step 2: create a textStream object

There are three properties in parentheses

4. The absolute path to the file

5. File constant read only =1, only write =2, add =8 permissions. (ForReading, ForWriting, or ForAppending.) ;

6. If a Boolean value is allowed to be created, it is true; otherwise, it is false;

Ex. :
 
Var f=fso.opentextfile( " C:a.txt " ,1 . true); 

Step 3: call the read method

1. Read (to Read the specified number of characters in the file)

2. ReadLine (reads a whole line, but not a newline)

3. ReadAll (then read the entire contents of the text file);

Determines if the last row is read
 
while (!f.AtEndOfStream) 
{ 
f.Readline(); 
} 

Step 4:

Close the textStream object:

Example: f. lose ();

Here is an example of an HTML open TXT file.
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
<title> hello </title> 
</head> 

<body> 
<div id="aa"></div> 

<script language="javascript"> 
var fso, ts, s ; 
var ForReading = 1; 

fso = new ActiveXObject("Scripting.FileSystemObject"); 
ts = fso.OpenTextFile("d:\testfile.txt", ForReading); 
s = ts.ReadLine(); 
document.getElementById("aa").innerHTML=s; 
</script> 

</body> 
</html> 

Related articles: