Ways to manipulate local folders using ActiveXObject in JavaScript

Source: Internet
Author: User
Tags file copy file system parent directory readfile readline root directory
I used to use vbscript to manipulate the folder, only to find that the original use of JavaScript is also possible, certainly not as simple as vbs, but it is good to learn.

On the Windows platform, js can call many ActivexObjects provided by Windows. This article uses js to implement document processing, and a simple introduction to writing ActiveX using js. The code is as follows: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title> New Document </title> </head> <script type=" Text/javascript"> function readFolder(){ var filePath = "d:test"; var fso = new ActiveXObject("Scripting.FileSystemObject"); //Load control var f = fso.GetFolder(filePath); var underFiles = new Enumerator (f.files); / / folder file for (;!underFiles.atEnd (); underFiles.moveNext ()) { var fn = "" + underFiles.item (); / / alert (fn); var Content = readFile(fn,fso); alert(content); } } function readFile(path,fso){ var f1 = fso.GetFile(path); var fh = fso.OpenTextFile(f1, 1/*reading*/) ; var content = ''; while ( !fh.AtEndOfStre Am ) { content += fh.ReadLine(); } fh.close() return content; } function writeExcel(){ var ExcelApp = new ActiveXObj ect("Excel.Application"); var ExcelSheet = new ActiveXObject("Excel.Sheet "); ExcelSheet.Application.Visible = true; ExcelSheet.ActiveSheet.Cells(1,1).Value = "This is column A, row 1"; ExcelSheet.SaveAs("d:TEST.XLS"); ExcelSheet.Application .Quit(); } </script> <body> <input type="button" value="traversing the folder" onclick="readFolder()"> <input type="button" value="write excel" onclick= "writeExcel()"> </body> </html>


The ActiveXObject object in JavaScript is a reference that enables and returns an Automation object.

Usage: newObj = new ActiveXObject( servername.typename[, location])
The ActiveXObject object syntax has these parts: where newObj is mandatory. The name of the variable to be assigned to ActiveXObject. Servername is required. The name of the application that provides the object. Typename is required. The type or class of the object to create. Location is optional. The name of the web server that created the object.
 Remember: ActiveX is a Microsoft thing, so this stuff is only supported by IE!

JavaScript uses ActiveXObject to create a FileSystemObject action file
 
First, the function realization core:

FileSystemObject object To implement file manipulation functions in javascript, the main thing is to rely on the FileSystemobject object.


Second, FileSystemObject programming Using the FileSystemObject object for programming is very simple, generally through the following steps: Create a FileSystemObject object, apply related methods, access object related properties.

(1) Create a FileSystemObject object The code for creating a FileSystemObject object is as long as 1 line: var fso = new ActiveXObject("Scripting.FileSystemObject"); After the above code is executed, fso becomes a FileSystemObject object instance.
(2) application related methods After creating an object instance, you can use the object's related 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) Accessing object related properties To access the related properties of the object, first establish a handle to the object, which is achieved through the get series method: GetDrive is responsible for obtaining the drive information, GetFolder is responsible for obtaining the folder information, and GetFile is responsible for obtaining the file information. For example, after pointing to the following code, f1 becomes the 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 relevant properties of the object. For example: The code is as follows:
Var fso = new ActiveXObject("Scripting.FileSystemObject"); var f1 = fso.GetFile("c:myjstest.txt"); alert("File last modified: " + f1.DateLastModified); After executing the last sentence above, Displays the last modified date attribute value of c:myjstest.txt. But one thing to note: For objects created using the create method, you don't have to use the get method to get the object handle. In this case, the handle name created by the create method can be used directly: The code is as follows:
Var fso = new ActiveXObject("Scripting.FileSystemObject"); var f1 = fso.createtextfile("c:myjstest.txt",true"); alert("File last modified: " + f1.DateLastModified);

Third, the operation of the drive (Drives) Using the FileSystemObject object to program the drive (Drives) and folders (Folders) is very eas y, which is like interacting with files in the Windows file browser, such as: copy, move folders, Get the properties of the folder.
 (1) Drives object properties The Drive object is responsible for collecting the contents of physical or logical drive resources in the system. It has the following attributes: l TotalSize: The size of the drive calculated in bytes. l AvailableSpace or FreeSpace: The available space of the drive in bytes (bytes). l DriveLetter: drive letter. l DriveType: Drive type, the value is: removable (fixed media), fixed (fixed media), network (network resources), CD-ROM or RAM disk. l SerialNumber: The serial number of the drive. l FileSystem: The file system type of the drive, which is FAT, FAT32, and NTFS. l IsReady: Whether the drive is available. l ShareName: The share name. l VolumeName: The name of the volume label. l Path and RootFolder: The path or root name of the drive.
(2) Drive object operation routines The following routines display the drive C's volume label, total capacity and available space and other information: The code is as follows:
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"; alert(s);

Fourth, the operation folder (Folders) operations related to the folder include creating, moving, deleting and obtaining related properties. 

Folder object operation routine: The following routine will practice to get the parent folder name, create a folder, delete the folder, determine whether it is the root directory, etc. 

The code is as follows:

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


Fifth. Operation files (Files) 

The operation of the file is more than the above The Drive and Folder operations are more complicated and basically divided into the following two categories: creation, copying, moving, deleting, and creating, adding, deleting, and reading of file contents. . The details are described below.

(1) create a file There are three ways to create an empty text file, sometimes called a text stream (text stream).



The first is to use the CreateTextFile method.
code show as below:   
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, ForWriting The value is 2.
The code is as follows: The code is as follows: var fso, ts; var ForWriting= 2; fso = new ActiveXObject("Scripting.FileSystemObject"); ts = fso.OpenTextFile("c:test.txt", ForWriting, true); To use the OpenAsTextStream method, also set the ForWriting property. The code is as follows: 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);

(2) add data to the file
After the file is created, generally follow the steps of "Open File -> Fill Data -> Close File" to add data to the file. To open a file, use the OpenTextFile method of the FileSystemObject object, or use the OpenAsTextStream method of the File object. Fill in the data to use the Write, WriteLine or WriteBlankLines methods of the TextStream object. In the same function of writing data, the difference between the three is that the Write method does not add a new line break at the end of the write data, the WriteLine method adds a new line break at the end, and WriteBlankLines adds one or more spaces. Row. Close the file to use the Close method of the TextStream object.

(3) create files and add data routines
 The following code combines the steps of creating a file, adding data, and closing a file: The code is as follows:
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 tf. WriteLine("Testing 1, 2, 3.") ; // Add 3 blank lines tf.WriteBlankLines(3) ; // Fill in a line without the line break tf.Write ("This is a test."); / / Close the file tf.Close();

(4) Reading the contents of the file
 To read data from a text file, use 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 an entire line, but does not include a newline character; the ReadAll method reads the entire contents of a text file. The read content is stored in a string variable for display and analysis. When using the Read or ReadLine method to read the contents of a file, if you want to skip some parts, use the Skip or SkipLine method. The following code demonstrates opening a file, filling in the data, and then reading the data: The code is as follows:
Var fso, f1, ts, s; var ForReading = 1; fso = new ActiveXObject("Scripting.FileSystemObject"); // Create file f1 = fso.CreateTextFile("c:testfile.txt", true); // Fill in One line of data f1.WriteLine("Hello World"); f1.WriteBlankLines(1); // Close the file f1.Close(); // Open the file ts = fso.OpenTextFile("c:testfile.txt", ForReading); // Read a line of content from the file to the string s = ts.ReadLine(); // Display the string information alert("File contents = '" + s + "'"); // Close the file ts.Close();

(5) Moving, copying and deleting files
For the above three file operations, javascript has two corresponding methods: File.Move or FileSystemObject.MoveFile for moving files; File.Copy or FileSystemObject.CopyFile for copying files; File.Delete or FileSystemObject.DeleteFile for deleting file. The following code demonstrates creating a text file in the root directory of drive C, filling in some content, then moving the file to the tmp directory, then creating a file copy under the directory temp, and finally deleting the files in both directories: The code is as follows :
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 f1.Close(); // Get the C: root file handle f2 = fso.GetFile("c:testfile.txt"); // Move the file to the tmp directory f2 .Move ("c:tmptestfile.txt"); // Copy the file to the temp directory f2.Copy ("c:temptestfile.txt"); // Get the file handle f2 = fso.GetFile("c:tmptestfile.txt "); f3 = fso.GetFile("c:temptestfile.txt"); // Delete file f2.Delete(); f3.Delete();

Sixth. Conclusion
 Through the above introduction and examples of the various objects, properties and methods of FileSystemObject, I believe that you have a clear understanding of how to use the javascript language to operate drives, files and folders in the page. However, the above mentioned routines are very simple. To master the javascript file operation technology comprehensively and flexibly, a lot of practical exercises are needed. And there is another reminder that because of the advanced operations involved in file reading and writing in the browser, for the default browser security level, there will be a message prompt before the code runs. Please do this in the actual environment. Prompt visitors to pay attention.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.