How to read local files and directories by JS

Source: Internet
Author: User
Tags parent directory readline

JavaScript is a Web page production can not be separated from the scripting language, relying on it, a Web page content is lively, full of vitality. But maybe you haven't found and applied some of its more advanced

The function of it. For example, files and folders to read, write and delete, as in VB, VC and other high-level languages often do the same job. Well, do you need to know about this?

General Then follow me. This article describes in detail how to use the JavaScript language for file operations.

First, the function realizes the core: FileSystemObject object

In fact, to implement the file operation function in JavaScript, the main thing is to rely on the FileSystemObject object. In a detailed description of the properties and methods of the FileSystemObject object

Before using the details, let's take a look at what objects and collections this object includes:

Ii. FileSystemObject Programming Trilogy

Programming with a FileSystemObject object is simple, typically through the following steps: Creating FileSystemObject objects, applying related methods, and accessing object-related properties.

(i) Creating FileSystemObject objects

The code to create the FileSystemObject object takes only 1 lines:

var fso = new ActiveXObject ("Scripting.FileSystemObject");

After the above code executes, the FSO becomes a FileSystemObject object instance.

(ii) Application of relevant methodologies

After you create an object instance, you can use the associated methods of the object. For example, use the CreateTextFile method to create a text file:

var fso = new ActiveXObject ("Scripting.FileSystemObject");

var f1 = fso.createtextfile ("C://myjstest.txt", true);

(iii) Access to object-related properties

To access the related properties of an object, first establish a handle to the object, which is done through the Get series method: Getdrive is responsible for obtaining the drive information, GetFolder is responsible for obtaining the text

Folder information, GetFile is responsible for obtaining 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. Like what:

var fso = new ActiveXObject ("Scripting.FileSystemObject");

var f1 = fso. GetFile ("C://myjstest.txt");

Alert ("File Last modified:" + F1.) DateLastModified);

After the last sentence is executed, the last modified Date attribute value for C:/myjstest.txt is displayed.

But one thing. Note: For objects created using the Create method, you do not have to use the Get method to obtain the object handle, and then the handle name created directly by using the Create method can be

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 driver (drives)

It is easy to use the FileSystemObject object to programmatically manipulate drives (drives) and folders (Folders), which is like interacting with files in a Windows file browser

, such as: Copy, move folder, get the properties of the folder.

A Drives Object Properties

The drive object is responsible for collecting the contents of the physical or logical drive resource in the system, which has the following properties:

L TotalSize: The drive size in bytes (byte).

L availablespace or FreeSpace: drive free space calculated in bytes (byte).

L DriveLetter: drive letter.

L DriveType: Drive type, value is: removable (mobile media), fixed (fixed media), Network (network Resource), CD-ROM, or RAM disk.

L SerialNumber: Serial code for the drive.

L FileSystem: The file system type of the drive on which the value is fat, FAT32, and NTFS.

L IsReady: The drive is available.

L ShareName: share name.

L VolumeName: Volume label name.

L Path and RootFolder: The path of the drive or the name of the root directory.

Two Drive object Operation routines

The following routines show information such as the volume label, Total capacity, and free 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";

alert (s);


Iv. Operation folder (Folders)

Actions that involve folders include creating, moving, deleting, and getting related properties.

A List of related properties and methods for the folder object

Two Folder object Operation routines

The following routines practice getting the parent folder name, creating a folder, deleting a folder, and determining whether it is a root directory, and so on:

var fso, fldr, S = "";

Create a FileSystemObject object instance

FSO = new ActiveXObject ("Scripting.FileSystemObject");

Get Drive Object

Fldr = fso. GetFolder ("c://");

Show Parent directory Name

Alert ("Parent folder name is:" + Fldr + "n");

Show Drive name

Alert ("contained on drive" + Fldr.) Drive + "n");

Determine if the root directory

if (Fldr. IsRootFolder)

Alert ("This is the root folder.");

Else

Alert ("This folder isn ' t a root folder.");

Alert ("/n/n");

Create a new Folder

Fso. CreateFolder ("C://bogus");

Alert ("Created folder C://bogus" + "n");

Displays the folder base name, not including the path name

Alert ("Basename =" + FSO.) Getbasename ("C://bogus") + "n");

Delete the Created folder

Fso. DeleteFolder ("C://bogus");

Alert ("Deleted folder C://bogus" + "n");

V. Operating documents (FILES)

The operation of the file is more complex than the drive (Drive) and folders (folder) described above, and is basically divided into the following two categories: creating, copying, moving, deleting files

In addition to manipulating and creating, adding, deleting, and reading operations on the contents of a file. The details are detailed below.

(i) Create a file

There are 3 ways to create an empty text file, which is sometimes called a text stream.

The first is the use of 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, the ForWriting value is 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, 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);

(ii) Adding data to documents

When a file is created, you typically add data to a file by following the steps of "Open file-> fill data-> close file."

You can open a file by using the OpenTextFile method of the FileSystemObject object, or by using the OpenAsTextStream method of the file object.

Fill in the data to use the Write, WriteLine, or WriteBlankLines method of the TextStream object. The difference between the 3 and the same is the ability to write data: Write

method does not add a new line break at the end of the write data, the WriteLine method adds a new newline character at the end, and WriteBlankLines adds one or more blank lines.

You can use the Close method of the TextStream object by closing the file.

(iii) Create files and add data routines

The following code combines several steps to create a file, add data, and close a 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 line breaks

Tf. WriteLine ("Testing 1, 2, 3.");

Add 3 Blank Lines

Tf. WriteBlankLines (3);

Fill in a line without line breaks

Tf. Write ("This is a test.");

Close File

Tf. Close ();

(iv) Read the contents of the file

Reading data from a text file uses the read, ReadLine, or ReadAll method of the TextStream object. The Read method is used to read a specified number of characters in a file; ReadLine method

Reads an entire line, but does not include line breaks; the ReadAll method reads the entire contents of the text file. The read content is stored in a string variable for display, parsing. In the use of Read or

ReadLine method to read the contents of a file, if you want to skip some parts, you need to use the skip or SkipLine method.

The following code shows opening the 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 one line of data

F1. WriteLine ("Hello World");

F1. WriteBlankLines (1);

Close File

F1. Close ();

Open File

TS = fso. OpenTextFile ("C://testfile.txt", ForReading);

Read a file line to a string

s = ts. ReadLine ();

Display string Information

Alert ("File contents = '" + S + "");

Close File

Ts. Close ();

(v) Moving, copying and deleting documents

For the above three file operations, JavaScript has two corresponding methods: File.move or filesystemobject.movefile for moving files; File.Copy or

Filesystemobject.copyfile is used to copy files, File.delete or filesystemobject.deletefile to delete files.

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, and then creating a file under the directory/temp

Copies, and finally deletes the files for these two 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 File

F1. Close ();

Get the file handle in the c:/root directory

F2 = fso. GetFile ("C://testfile.txt");

Move files to/tmp directory

F2. Move ("C://tmp//testfile.txt");

Copy files to the/temp directory

F2. Copy ("C://temp//testfile.txt");

Get file Handle

F2 = fso. GetFile ("C://tmp//testfile.txt");

F3 = FSO. GetFile ("C://temp//testfile.txt");

deleting files

F2. Delete ();

F3. Delete ();

Six, the conclusion

Using the above descriptions and examples of the various objects, properties, and methods of FileSystemObject, I believe you have been working on how to use the JavaScript language in the page to manipulate drives, files, and

The folder has a clear understanding. However, the above mentioned routines are very simple, to fully and flexibly grasp the JavaScript file operation technology, but also need a lot of practical practice. but also

One caveat is that because of advanced operations involving file reading and writing in a browser, there is a message before the code runs for the default level of browser security

Shown

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.