JavaScript File Operations _ Basics

Source: Internet
Author: User
Tags parent directory readline
First, the function realizes the core: FileSystemObject object
To implement the file manipulation function in JavaScript, the main thing is to rely on the FileSystemObject object.
Second, FileSystemObject programming
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, you first establish a handle to the object, which is done by the Get series method: Getdrive is responsible for obtaining the drive information, GetFolder is responsible for obtaining the folder information, GetFile is responsible for obtaining 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. 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)
Using the FileSystemObject object to programmatically manipulate drives (drives) and folders (Folders) is easy, like interacting with files in a Windows file browser, such as copying, moving folders, and getting the properties of a folder.
(i) 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.
(ii) Drive object manipulation 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.
Folder object Action 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 \ nthe");
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)
Operations on files are more complex than the drives (Drive) and folders (folder) described above, and are essentially grouped into the following two categories: creation, copying, movement, deletion, and creation, addition, deletion, and reading of file content. 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 these 3 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 newline character at the end, and WriteBlankLines adds one or more blank rows.
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; the ReadLine method reads an entire line, but does not include a newline character; the ReadAll method reads the entire contents of the text file. The read content is stored in a string variable for display, parsing.



Method or attribute Description
BuildPath ()
Generate a file path
CopyFile () Copy files
CopyFolder () Copy directory
CreateFolder () Create a new directory
CreateTextFile () generates a file
DeleteFile () Deletes a file
DeleteFolder () Deletes a directory
Driveexists () Check whether the letter exists
Drives a collection of returned disk characters
FileExists () Verify that the file exists
FolderExists Check if a directory exists
Getabsolutepathname () Gets the absolute path of a file
Getbasename () Get filename
Getdrive () Get the letter name
GetDriveName () Get the letter name
Getextensionname () to obtain the suffix of the file
GetFile () Generating File objects
GetFileName () Get filename
GetFolder () Get directory Object
Getparentfoldername gets the parent directory name of the file or directory
GetSpecialFolder () Get a special directory name
GetTempName () generates a temporary file object
MoveFile () Moving files
MoveFolder () Mobile Directory
OpenTextFile () opens a file stream


F.files//directory of all Files set
F.attributes//File properties
Case 0 str= "normal file. No properties are set. "
Case 1 Str= "read-only file. can read and write. "
Case 2 Str= "hides the file. can read and write. "
Case 4 Str= "system files. can read and write. "
Case str= folder or directory. Read-only. "
Case str= The file that has changed since the last backup. can read and 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 Modified time
F.path//file path
F.name//File name
F.type//File type
F.size//File Size (units: bytes)
F.parentfolder//Parent Directory
F.rootfolder//root directory

Example description

BuildPath (path, filename)//This method adds a file to the given path and automatically adds a delimiter
<script language= "JavaScript" >
<!--
var fso = new ActiveXObject ("Scripting.FileSystemObject");
var NewPath = fso. BuildPath ("C:\\tmp", "51js.txt"); Path to generate C:\tmp\51js.txt
alert (NewPath);
-->
</SCRIPT>

CopyFile (source file, target file, overwrite)//copy source file to target file, when the overwrite value is true, if the target file exists will overwrite the file
<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 object directory to target directory, when overridden to true, if target directory exists will overwrite file
<script language= "JavaScript" >
<!--
var fso = new ActiveXObject ("Scripting.FileSystemObject");
Fso. CopyFolder ("C:\\windows\\desktop", "d:\\"); Copy the Desktop directory of C disk to the root of D disk
-->
</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 the C disk
-->
</SCRIPT>

CreateTextFile (filename, overwrite)//Create a new file, if this file already exists, you need to set the override value to True
<script language= "JavaScript" >
<!--
var fso = new ActiveXObject ("Scripting.FileSystemObject");
var newfileobject = fso. CreateTextFile ("C:\\autoexec51js.bat", true); The script will create a file called Autoexec51js.bat on the C disk
-->
</SCRIPT>

DeleteFile (filename, read-only?) //Delete a file, if the file's properties are read-only, you need to set the read-only value to True
<script language= "JavaScript" >
<!--
var fso = new ActiveXObject ("Scripting.FileSystemObject"); To be safe, I'm going to back up the Autoexec.bat you want to delete to your D disk.
var NewPath = fso. CopyFile ("C:\\autoexec.bat", "D:\\autoexec.bat"); Remove the Autoexec.bat file from the C-disk
Fso. DeleteFile ("C:\\autoexec.bat", true);
-->
</SCRIPT>

DeleteFolder (filename, read-only?) //Delete a directory, if the directory's properties are read-only, you need to set the read-only value to True
<script language= "JavaScript" >
<!--
var fso = new ActiveXObject ("Scripting.FileSystemObject");
Fso. CopyFolder ("C:\\windows\\desktop", "d:\\"); For security, I'm going to copy your C-Disk desktop directory to the root of your D disk.
Fso. DeleteFolder ("C:\\windows\\desktop", true); Remove your desktop directory, but because desktop is something of the system, it can't be deleted, but ...
-->
</SCRIPT>

Driveexists (letter)//check whether a disk exists, if the existence of the return will be true, do not exist on the back ....
<script language= "JavaScript" >
<!--
var fso = new ActiveXObject ("Scripting.FileSystemObject");
hasdrived = fso. Driveexists ("D"); Check if the system has D disk presence
Hasdrivez = fso. Driveexists ("Z"); Check if the system has a Z disk present
if (hasdrived) alert ("There is a D disk in your system");
if (!hasdrivez) alert ("There is no Z-disk in your system");
-->
</SCRIPT>

FileExists (filename)//Check whether a file exists, if there is a return to true, does not exist on the return ....
<script language= "JavaScript" >
<!--
var fso = new ActiveXObject ("Scripting.FileSystemObject");
FileName = fso. FileExists ("C:\\autoexec.bat");
if (fileName) alert ("You have Autoexec.bat file in C disk, press OK after this file will be deleted!") "); A joke:
-->
</SCRIPT>

FolderExists (directory name)//check whether a directory exists, if there is a return to true, does not exist to return ....
<script language= "JavaScript" >
<!--
var fso = new ActiveXObject ("Scripting.FileSystemObject");
FolderName = fso. FolderExists ("c:\\windows\\fonts");
if (folderName) alert ("Press OK after the system's font will be deleted!") "); A 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)//return filename of File object
<script language= "JavaScript" >
<!--
var fso = new ActiveXObject ("Scripting.FileSystemObject");
BaseName = fso. Getbasename ("C:\\autoexec.bat"); Gets the filename of the Autoexec.bat AutoExec
alert (baseName);
-->
</SCRIPT>

Getextensionname (File object)//file suffix
<script language= "JavaScript" >
<!--
var fso = new ActiveXObject ("Scripting.FileSystemObject");
Exname = fso. Getextensionname ("C:\\autoexec.bat"); Get Autoexec.bat suffix Bat
alert (exname);
-->
</SCRIPT>

Getparentfoldername (File object)//Get Parent directory Name
<script language= "JavaScript" >
<!--
var fso = new ActiveXObject ("Scripting.FileSystemObject");
ParentName = fso. Getparentfoldername ("C:\\autoexec.bat"); Get Autoexec.bat's parent directory C-Disk
alert (ParentName);
-->
</SCRIPT>

GetSpecialFolder (Directory code)//Get the path of some special directories in the system, the directory code has 3 is 0: Install Windows directory 1: System files directory 2: Temporary files directory
<script language= "JavaScript" >
<!--
var fso = new ActiveXObject ("Scripting.FileSystemObject");
Tmpfolder = fso. GetSpecialFolder (2); Get the path to the system temp file directory as mine is C:\windows\temp.
alert (Tmpfolder);
-->
</SCRIPT>

GetTempName ()//generates a random temporary file object that follows the RAD lead followed by random numbers as if some software were to be generated during installation *.tmp
<script language= "JavaScript" >
<!--
var fso = new ActiveXObject ("Scripting.FileSystemObject");
Tmpname = fso. GetTempName (); I created a raddb70e.tmp when I was testing it.
alert (tmpname);
-->
</SCRIPT>

MoveFile (source file, target file)//move the source file to the location of the destination 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 in C to disk 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.