JavaScript USES ActiveXObject to manipulate local folder methods

  • 2020-03-30 02:29:02
  • OfStack

On the Windows platform, js can call many Windows provided ActivexObject, this article USES js to achieve document processing, and USES js to write ActiveX to do a simple introduction.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "">
  <title> New Document </title>
<script type="text/javascript">
 function readFolder(){
 var filePath = "d:\test\";
 var fso = new ActiveXObject("Scripting.FileSystemObject");   //The load control
 var f = fso.GetFolder(filePath);
 var underFiles = new Enumerator(f.files); //File under folder
for (;!underFiles.atEnd();underFiles.moveNext()){   
             var fn = "" + underFiles.item();   
          var content = readFile(fn,fso);
function readFile(path,fso){
var f1 = fso.GetFile(path);
var fh = fso.OpenTextFile(f1, 1);
               var content = '';
               while ( !fh.AtEndOfStream ) {
                      content += fh.ReadLine();
      return content;
function writeExcel(){
 var ExcelApp = new ActiveXObject("Excel.Application");
  var ExcelSheet = new ActiveXObject("Excel.Sheet");
  ExcelSheet.Application.Visible = true;
 ExcelSheet.ActiveSheet.Cells(1,1).Value = "This is column A, row 1";
  <input type="button" value=" Traversal folder " onclick="readFolder()">
<input type="button" value=" write excel" onclick="writeExcel()">

The ActiveXObject object in JavaScript is a reference to the Automation object that is enabled and returned. Usage:

NewObj = new ActiveXObject(servername.typename[, location])

The ActiveXObject object syntax has these sections: where newObj is required. The variable name to assign to ActiveXObject.
Servername is a required option. The name of the application that provides the object.
Typename is a mandatory option. The type or class of the object to be created.
Location is optional. The name of the network server where the object is created.

JavaScript USES ActiveXObject to create the FileSystemObject action file

1. Core function implementation: FileSystemObject

To implement the file manipulation function in javascript, we mainly rely on the FileSystemobject.

Second, FileSystemObject programming

Programming with a FileSystemObject is simple, typically by creating the FileSystemObject, applying the associated methods, and accessing the associated properties of the object.

(1) create a FileSystemObject

The code to create the FileSystemObject is only 1 line:
Var fso = new ActiveXObject (" Scripting. FileSystemObject ");
After the above code is executed, fso becomes a FileSystemObject instance.

(ii) application of relevant methods

After you create an object instance, you can use the object's associated methods. For example, create a text file using the CreateTextFile method:
Var fso = new ActiveXObject (" Scripting. FileSystemObject ");
Var f1 = fso. Createtextfile (" c: \ \ myjstest TXT, "true");
(3) access object related properties
To access the properties of an object, you first create a handle to the object through a series of get methods: GetDrive gets the drive information, GetFolder gets the folder information, and GetFile gets the file information. For example, after pointing to the following code, f1 becomes a handle to the file c:\test.txt:
Var fso = new ActiveXObject (" Scripting. FileSystemObject ");
Var f1 = fso. GetFile (" c: \ \ myjstest TXT ");
Then, use f1 to access the associated properties of the object. Such as:

var fso = new ActiveXObject("Scripting.FileSystemObject");
var f1 = fso.GetFile("c:\myjstest.txt");
alert("File last modified: " + f1.DateLastModified);

After the last sentence above is executed, the last modified date property value of c:\myjstest.txt is displayed.
One thing to note, however, is that for objects created with the create method, you no longer need to use the get method to get the object handle. Instead, you can simply use the create method to create the handle name:

var fso = new ActiveXObject("Scripting.FileSystemObject");
var f1 = fso.createtextfile("c:\myjstest.txt",true");
alert("File last modified: " + f1.DateLastModified);

Iii. Operating Drives (Drives)

Using the FileSystemObject object to program operations on Drives and Folders is as easy as interacting with files in the Windows file browser, such as copying, moving Folders, and getting folder properties.
(a) the Drives object property
The Drive object, which collects the contents of the physical or logical Drive resources in the system, has the following properties:
L TotalSize: drive size in bytes.
L AvailableSpace or FreeSpace: the space available on a drive in bytes.
L DriveLetter: DriveLetter.
L DriveType: drive type, value is: removable medium (mobile), fixed (fixed) medium, network (network resources), CD - ROM or RAM disk.
L SerialNumber: serial code for the drive.
FileSystem: the FileSystem type of the drive, with values of FAT, FAT32, and NTFS.
L IsReady: is the drive available?
L ShareName: Shared name.
L VolumeName: volume label name.
Path and RootFolder: the Path or root directory name of the drive.

(2) Drive object operation routine

The following routines show the volume label, total capacity, and available space of drive C:

var fso, drv, s ="";
fso = new ActiveXObject("Scripting.FileSystemObject");
drv = fso.GetDrive(fso.GetDriveName("c:\"));
s += "Drive C:" + "  �  ";
s += drv.VolumeName + "n";
s += "Total Space: " + drv.TotalSize / 1024;
s += " Kb" + "n";
s += "Free Space: " + drv.FreeSpace / 1024;
s += " Kb" + "n";

Iv. Operation Folders

Operations involving folders include creating, moving, deleting, and getting related properties.
Folder object operation routine:
The following routines will practice getting a parent folder name, creating a folder, deleting a folder, determining whether it is a root directory, and so on:

var fso, fldr, s = "";
//Create the FileSystemObject object instance
fso = new ActiveXObject("Scripting.FileSystemObject");
//Get Drive object
fldr = fso.GetFolder("c:\");
//Displays the parent directory name
alert("Parent folder name is: " + fldr + "n");
//Displays the drive name
alert("Contained on drive " + fldr.Drive + "n");
//Determines whether it is the root directory
if (fldr.IsRootFolder)
alert("This is the root folder.");
alert("This folder isn't a root folder.");
//Create a new folder
fso.CreateFolder ("C:\Bogus");
alert("Created folder C:\Bogus" + "n");
//Displays the folder base name without pathname
alert("Basename = " + fso.GetBaseName("c:\bogus") + "n");
//Delete the created folder
fso.DeleteFolder ("C:\Bogus");
alert("Deleted folder C:\Bogus" + "n");

V. operating Files

Operations on files are more complex than the drives and folders described above, and are basically divided into two categories: create, copy, move, and delete operations on files, and create, add, delete, and read operations on file contents. Details are given below.
(I) create documents
There are three ways to create an empty text file, sometimes called a text stream.
The first is to use the CreateTextFile method. The code is as follows:

var fso, f1;
fso = new ActiveXObject("Scripting.FileSystemObject");
f1 = fso.CreateTextFile("c:\testfile.txt", true);

The second is to use the OpenTextFile method and add the ForWriting property, which has a value of 2. The code is as follows:

var fso, ts;
var ForWriting= 2;
fso = new ActiveXObject("Scripting.FileSystemObject");
ts = fso.OpenTextFile("c:\test.txt", ForWriting, true);

The third is to use the OpenAsTextStream method, again setting the ForWriting property.

var fso, f1, ts;
var ForWriting = 2;
fso = new ActiveXObject("Scripting.FileSystemObject");
fso.CreateTextFile ("c:\test1.txt");
f1 = fso.GetFile("c:\test1.txt");
ts = f1.OpenAsTextStream(ForWriting, true);

(ii) add data to the file

When a file is created, always follow the "open file -> Fill in the data -> The "close file" step accomplishes the purpose of adding data to the file.
Open files using the OpenTextFile method of the FileSystemObject object or the OpenAsTextStream method of the File object.
To fill in the data, use the Write, WriteLine, or WriteBlankLines method to the TextStream object. The difference between the three is that the Write method does not add a new line at the end of the Write, the WriteLine method adds a new line at the end, and WriteBlankLines adds one or more blank lines.
Close the file using the Close method of the TextStream object.

(3) create files and add data routines

The following code applies a combination of creating a file, adding data, and closing the file:

var fso, tf;
fso = new ActiveXObject("Scripting.FileSystemObject");
//Create a new file
tf = fso.CreateTextFile("c:\testfile.txt", true);
//Fill in the data and add a newline character
tf.WriteLine("Testing 1, 2, 3.") ;
//Add 3 blank lines
tf.WriteBlankLines(3) ;
//Fill in a line without newline
tf.Write ("This is a test.");
//Close the file

(4) reading the contents of the document

Reading data from a text file USES the Read, ReadLine, or ReadAll methods of the TextStream object. The Read method is used to Read a specified number of characters in a file. The ReadLine method reads a full line, but not a newline; The ReadAll method reads the entire contents of the text file. The read content is stored in a string variable for display and analysis. When reading the contents of a file using the Read or ReadLine method, you use the Skip or SkipLine method if you want to Skip parts.
The following code demonstrates opening a file, filling in the data, and then reading the data:

var fso, f1, ts, s;
var ForReading = 1;
fso = new ActiveXObject("Scripting.FileSystemObject");
//Create a file
f1 = fso.CreateTextFile("c:\testfile.txt", true);
//Fill in a line of data
f1.WriteLine("Hello World");
//Close the file
//Open the file
ts = fso.OpenTextFile("c:\testfile.txt", ForReading);
//Reads a line from the file to the string
s = ts.ReadLine();
//Display string information
alert("File contents =  ' " + s + " ' ");
//Close the file

(5) to move, copy and delete documents

For the above three kinds of File operations, javascript each have two corresponding methods: File. Move or FileSystemObject. MoveFile to Move files; File. Copy or FileSystemObject. Used by CopyFile used to Copy files; File. Delete or FileSystemObject. DeleteFile used to Delete the File.
The following code demonstrates creating a text file in the root of drive C, filling in some content, then moving the file to the directory \ TMP, then creating a copy of the file under the directory \temp, and finally deleting the files in both directories:

var fso, f1, f2, s;
fso = new ActiveXObject("Scripting.FileSystemObject");
f1 = fso.CreateTextFile("c:\testfile.txt", true);
//Write a line
f1.Write("This is a test.");
//Close the file
//Gets the file handle under the C: root
f2 = fso.GetFile("c:\testfile.txt");
//Move the file to the directory  TMP
f2.Move ("c:\tmp\testfile.txt");
//Copy the file to the directory temp
f2.Copy ("c:\temp\testfile.txt");
//Gets the file handle
f2 = fso.GetFile("c:\tmp\testfile.txt");
f3 = fso.GetFile("c:\temp\testfile.txt");
//Delete the file

Six, knot

Through the above introduction and examples of the various objects, properties, and methods of the FileSystemObject, I believe you have a clear understanding of how to use the javascript language to manipulate drives, files, and folders on a page. However, the routines mentioned above are very simple, and it takes a lot of practice to master javascript file manipulation techniques comprehensively and flexibly. It is also important to note that, because of the advanced operations involved in reading and writing files in the browser, the default browser security level is always prompted with a message before the code runs, which should be alerted to the visitor in the real world.

Related articles: