File Operations in Javascript

Source: Internet
Author: User

I. function implementation core: FileSystemObject object
To implement file operations in javascript, FileSystemobject objects are primarily used.
Ii. FileSystemObject Programming
It is very easy to program with FileSystemObject object. Generally, the following steps are required: Create a FileSystemObject object, apply related methods, and access object attributes.
(1) create a FileSystemObject object
Only one line of code is required to create a FileSystemObject object:
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-related methods. 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 ");
(3) Access Object Attributes
To access the relevant properties of an object, you must first create a handle pointing to the object, which must be implemented through the get series method: GetDrive is responsible for obtaining the drive information, GetFolder is responsible for obtaining the folder information, getFile obtains the file information. For example, after pointing to the following code, f1 becomes the handle pointing 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 attributes of the object. For example:
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 of c: \ myjstest.txt is displayed.
Note: For objects created using the create method, you do not need to use the get method to obtain the object handle. In this case, you can directly use the name of the handle created using the create method:
Var fso = new ActiveXObject ("Scripting. FileSystemObject ");
Var f1 = fso. createtextfile ("c: \ myjstest.txt", true ");
Alert ("File last modified:" + f1.DateLastModified );
3. Drive)
It is easy to use FileSystemObject objects to program drive and folder operations, just like performing interactive operations on files in a Windows file browser, such as copying and moving Folders, obtain the attributes of a folder.
(1) Drives Object Attributes
The Drive object collects the content of physical or logical Drive resources in the system. It has the following attributes:
L TotalSize: the size of the drive in bytes.
L AvailableSpace or FreeSpace: The drive space in bytes.
L DriveLetter: drive letter.
L DriveType: Drive Type, value: removable (Mobile Medium), fixed (fixed medium), network (network Resources), CD-ROM or ramdisk.
L SerialNumber: the serial number of the drive.
L FileSystem: The file system type of the drive. Values: FAT, FAT32, and NTFS.
L IsReady: whether the drive is available.
L ShareName: Share Name.
L VolumeName: the name of the volume label.
L Path and RootFolder: The drive Path or root directory name.
(2) Drive object operation routine
The following routine displays 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 ";
Alert (s );
4. Folders)
Folder operations include creating, moving, deleting, and obtaining related properties.
Folder object operation routine:
The following routine obtains the parent folder name, creates a folder, deletes a folder, and determines whether the folder is the root directory:
Var fso, fldr, s = "";
// Create a 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 whether the root directory is used
If (fldr. IsRootFolder)
Alert ("This is the root folder .");
Else
Alert ("This folder isn't a root folder .");
Alert ("\ n ");
// Create a new folder
Fso. CreateFolder ("C: \ Bogus ");
Alert ("Created folder C: \ Bogus" + "\ n ");
// Display the basic folder name, excluding the path name
Alert ("Basename =" + fso. GetBaseName ("c: \ bogus") + "\ n ");
// Delete the created folder
Fso. DeleteFolder ("C: \ Bogus ");
Alert ("Deleted folder C: \ Bogus" + "\ n ");
5. Files)
The operations on files are more complex than the Drive and Folder operations described above. They are basically divided into the following two categories: create, copy, move, and delete objects, and create, add, delete, and read objects. The following describes in detail.
(1) create a file
There are three methods to create an empty text file, which is also called a text stream ).
The first method 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 method is to use the OpenTextFile method and add the ForWriting attribute. The value of ForWriting 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 method is to use the OpenAsTextStream method and set the ForWriting attribute. 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 a file
After a file is created, you can add data to the file by following the steps of "Open File> Fill in data> close file.
To open a File, you can use the OpenTextFile method of the FileSystemObject object or the OpenAsTextStream method of the File object.
Use the Write, WriteLine, or WriteBlankLines methods of the TextStream object to fill in the data. With 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 written data, and the WriteLine method must add a new line break at the end, writeBlankLines adds one or more empty lines.
To Close a file, use the Close method of the TextStream object.
(3) create a file and add a data routine
The following code combines the steps of creating a file, adding data, and closing a file for application:
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 line break
Tf. WriteLine ("Testing 1, 2, 3 .");
// Add 3 empty rows
Tf. WriteBlankLines (3 );
// Enter a line without a line break
Tf. Write ("This is a test .");
// Close the file
Tf. Close ();
(4) Reading File Content
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 a whole line, but does not include line breaks. The ReadAll method reads the entire content of a text file. The read content is stored in string variables for display and analysis.

Method or attribute description
BuildPath ()
Generate a file path
Copy file ()
CopyFolder () Copy directory
CreateFolder () create a new directory
CreateTextFile () to generate a file
DeleteFile () deletes an object.
DeleteFolder () deletes a directory
DriveExists () checks whether the drive letter exists
Drives returns a collection of drive letters.
FileExists () checks whether a file exists
FolderExists checks whether a directory exists
GetAbsolutePathName () gets the absolute path of a file
GetBaseName () Get the file name
GetDrive () gets the drive letter name
GetDriveName () gets the drive letter name
GetExtensionName () gets the file suffix
GetFile () generate a file object
GetFileName () Get the file name
GetFolder () to get the directory object
GetParentFolderName: Get the parent directory name of the file or directory
GetSpecialFolder () Get the special directory name
GetTempName () generates a temporary file object
MoveFile () Move a file
MoveFolder () Move directory
OpenTextFile () open a file stream

F. Files // all file sets in the directory
F. attributes // file attributes
Case 0 Str = "normal file. No attribute is set. "
Case 1 Str = "read-only file. Read/write. "
Case 2 Str = "hide a file. Read/write. "
Case 4 Str = "system file. Read/write. "
Case 16 Str = "folder or directory. Read-only. "
Case 32 Str = "files changed after the last backup. Read/write. "
Case 1024 Str = "link or shortcut. Read-only. "
Case 2048 Str = "compressed file. Read-only. "
F. Datecreated // Creation Time
F. DateLastAccessed // last access time
F. DateLastModified // last modification time
F. Path // file Path
F. Name // file Name
F. Type // file Type
F. Size // file Size (unit: bytes)
F. ParentFolder // parent directory
F. RootFolder // root directory

Instance description

BuildPath (path, file name) // This method will add a file to the specified path and automatically add the delimiter
<Script language = "JavaScript">
<! --
Var fso = new ActiveXObject ("Scripting. FileSystemObject ");
Var newpath = fso. BuildPath ("c: \ tmp", "51js.txt"); // generate the path of c: \ tmp \ 51js.txt
Alert (newpath );
-->
</SCRIPT>

CopyFile (source file, target file, overwrite) // copy the source file to the target file. When the overwrite value is true, if the target file exists, the file will be overwritten.
<Script language = "JavaScript">
<! --
Var fso = new ActiveXObject ("Scripting. FileSystemObject ");
Var newpath = fso. CopyFile ("c: \ autoexec. bat", "d: \ autoexec. bak ");
-->
</SCRIPT>

CopyFolder (Object directory, target directory, overwrite) // copy the object directory to the target directory. If it is set to true, the file will be overwritten if the target directory exists.
<Script language = "JavaScript">
<! --
Var fso = new ActiveXObject ("Scripting. FileSystemObject ");
Fso. CopyFolder ("c :\\ WINDOWS \ Desktop", "d :\\"); // copy the Desktop directory of drive c to the root directory of drive d.
-->
</SCRIPT>

CreateFolder (directory name) // create a new directory
<Script language = "JavaScript">
<! --
Var fso = new ActiveXObject ("Scripting. FileSystemObject ");
Var newFolderName = fso. CreateFolder ("c: \ 51JS"); // create a 51JS directory on drive c.
-->
</SCRIPT>

CreateTextFile (file name, overwrite) // create a new file. If the file already exists, set the overwrite value to true.
<Script language = "JavaScript">
<! --
Var fso = new ActiveXObject ("Scripting. FileSystemObject ");
Var newFileObject = fso. CreateTextFile ("c: \ autoexec51JS. bat", true); // The Script creates a file named autoexec51JS. bat on drive c.
-->
</SCRIPT>

DeleteFile (file name, read-only ?) // Delete an object. If the object attribute is read-only, set the read-only value to true.
<Script language = "JavaScript">
<! --
Var fso = new ActiveXObject ("Scripting. FileSystemObject"); // to ensure security, I first back up autoexec. bat to your D disk.
Var newpath = fso. CopyFile ("c: \ autoexec. bat", "d: \ autoexec. bat"); // Delete the autoexec. bat file of drive c.
Fso. DeleteFile ("c: \ autoexec. bat", true );
-->
</SCRIPT>

DeleteFolder (file name, read-only ?) // Delete a directory. If the Directory attribute is read-only, set the read-only value to true.
<Script language = "JavaScript">
<! --
Var fso = new ActiveXObject ("Scripting. FileSystemObject ");
Fso. copyFolder ("c :\\ WINDOWS \ Desktop", "d :\\"); // to ensure security, copy the Desktop directory of your drive c to the root directory of your drive d.
Fso. deleteFolder ("c: \ WINDOWS \ Desktop", true); // delete your Desktop directory. However, because desktop is a system item, you cannot delete it all, but .........
-->
</SCRIPT>

DriveExists (drive letter) // check whether a disk exists. If it exists, it returns true. If it does not exist, it returns .......
<Script language = "JavaScript">
<! --
Var fso = new ActiveXObject ("Scripting. FileSystemObject ");
HasDriveD = fso. DriveExists ("d"); // check whether the system has a d Disk
HasDriveZ = fso. DriveExists ("z"); // check whether the system has a Z Disk
If (hasDriveD) alert ("your system has a ddisk ");
If (! HasDriveZ) alert ("your system has no Z disk ");
-->
</SCRIPT>

FileExists (File Name) // check whether a file exists. If it exists, it returns true. If it does not exist, it returns .......
<Script language = "JavaScript">
<! --
Var fso = new ActiveXObject ("Scripting. FileSystemObject ");
FileName = fso. FileExists ("c: \ autoexec. bat ");
If (fileName) alert ("You have an autoexec. bat file in drive C. Press OK and the file will be deleted! "); // Joke :)
-->
</SCRIPT>

FolderExists (directory name) // check whether a directory exists. If it exists, it returns true. If it does not exist, it returns .......
<Script language = "JavaScript">
<! --
Var fso = new ActiveXObject ("Scripting. FileSystemObject ");
FolderName = fso. FolderExists ("c: \ WINDOWS \ Fonts ");
If (folderName) alert ("after you press OK, the font of the system will be deleted! "); // Joke :)
-->
</SCRIPT>

GetAbsolutePathName (file object) // returns the absolute path of the file object in the system.
<Script language = "JavaScript">
<! --
Var fso = new ActiveXObject ("Scripting. FileSystemObject ");
PathName = fso. GetAbsolutePathName ("c: \ autoexec. bat ");
Alert (pathName );
-->
</SCRIPT>

GetBaseName (file object) // returns the file name of the object.
<Script language = "JavaScript">
<! --
Var fso = new ActiveXObject ("Scripting. FileSystemObject ");
BaseName = fso. GetBaseName ("c: \ autoexec. bat"); // get the autoexec. bat file name autoexec
Alert (baseName );
-->
</SCRIPT>

GetExtensionName (file object) // file suffix
<Script language = "JavaScript">
<! --
Var fso = new ActiveXObject ("Scripting. FileSystemObject ");
ExName = fso. GetExtensionName ("c: \ autoexec. bat"); // obtain the suffix bat
Alert (exName );
-->
</SCRIPT>

GetParentFolderName (file object) // get the parent directory name
<Script language = "JavaScript">
<! --
Var fso = new ActiveXObject ("Scripting. FileSystemObject ");
ParentName = fso. GetParentFolderName ("c: \ autoexec. bat"); // obtain the parent directory c of autoexec. bat.
Alert (parentName );
-->
</SCRIPT>

GetSpecialFolder (directory code) // obtain the path of some special directories in the system. The directory code has three directories: 0: the directory where the Window is installed; 1: The system file directory; 2: the temporary file directory.
<Script language = "JavaScript">
<! --
Var fso = new ActiveXObject ("Scripting. FileSystemObject ");
TmpFolder = fso. GetSpecialFolder (2); // obtain the path of the temporary system file directory. For example, if my path is C: \ windows \ temp
Alert (tmpFolder );
-->
</SCRIPT>

GetTempName () // generate a random temporary file object. The random number is followed by a random number using rad, as if some software will generate *. tmp during installation.
<Script language = "JavaScript">
<! --
Var fso = new ActiveXObject ("Scripting. FileSystemObject ");
TmpName = fso. GetTempName (); // I generated radDB70E. tmp during the test.
Alert (tmpName );
-->
</SCRIPT>

MoveFile (source file, target file) // move the source file to the location of the target file
<Script language = "JavaScript">
<! --
Var fso = new ActiveXObject ("Scripting. FileSystemObject ");
Var newpath = fso. MoveFile ("c: \ autoexec. bat", "d: \ autoexec. bat"); // move the autoexec. bat file of drive c to drive d.
-->
</SCRIPT>

Related Article

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.