Opening and Closing Files

[ LiB ]

Opening and Closing Files

Having looked at the previous example, you should have a pretty good idea of how the FileSystemObject works and how to use it to instantiate other runtime objects, as well as how to use other runtime objects to access the Windows files system. Let's dig a little deeper in and learn how to use JScript's runtime object to create custom report and log files.

As demonstrated in the previous example, the first thing to do is to instantiate the FileSystemObject as shown here.

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

Once this is done, you should next check to find out whether the report or log file you plan on working with already exists, as demonstrated here.

 if (fsoObject.FileExists("c:\MyDocs\Summary.txt")) 


Take note of the use of the double backslashes in the previous statements. I had to use two slashes instead of one because in JScript, the \ character is a special character, so to use it I had to escape it, which means that I had to precede it with another slash character.

In this example, the FileSystemObject object's FileExists() method is used to determine whether a file named Summary.txt already exists in a folder called MyDocs on the computer's C drive. By first checking for the existence of a file, you provide the opportunity to decide which of the following should happen:

  • The script should open it and append new data to the end of it.

  • The script should create it if it does not exist.

  • The script should overwrite it with a new empty file.

To work with files, you first must open them. This is accomplished using the FileSystemObject object's OpenTextFile() method. This method requires that you pass it the following information:

  • The file's name and its path

  • The mode in which the file should be opened

  • Instruction on whether or not to create the file if it does not already exist

Table 6.8 lists the constants that define the mode in which the OpenTextFile() method opens text files.






Opens the specified file in read mode



Opens the specified file in write mode



Opens the specified file in append mode



Unfortunately, you can open a file only using one of the modes listed in Table 6.8.Therefore, if your script needs to both read and write to an output file, you will have to make sure that you close the file and reopen it using the appropriate mode each time you need to perform a different type of file processing operation.

Table 6.9 lists the two available choices that determine whether or not a new file will be created if one does not already exist.




Opens an existing file or creates and then opens a new file


Opens an existing file but will not create a new file if the specified file does not exist

Make sure that you take special care to specify the correct operation when opening a file. Otherwise, you'll run into problems. For example, if you open a file in ForWriting mode and a file of the same name already exists, that file will be overridden with a new file, resulting in the loss of all data previously stored in the file. By the same token, if you want to create a fresh new report each time your script runs, make sure that you open the output file in ForWriting mode and not in ForAppending mode. Otherwise, you'll end up with a report that keeps growing and growing, which is fine if you are creating a log file and not a fresh copy of a report.


Now seems like an opportune moment for me to mention that when you run a JScript using the WSH on a computer running Windows NT, XP, 2000, or 2003, that script runs using the same security access rights and permissions assigned to your user account. Therefore, if you do not have the capability to access or modify a given file manually, your scripts will not be able to work with it, either.


The trick to processing text files effectively using JScripts is to understand the purpose and location of the file pointer.The file pointer marks the location within a file where the next character typed will be placed.When a new file is first opened, the file pointer will be at row 0 and column 0.The first character entered into the file results in the pointer moving to column 1 in row 0.If a carriage return operation occurs,the file pointer moves to column 0 in the next row. Knowing the location of the file pointer is especially important if you need to read data from or write data to a file with a fixed record format, in which data is organized in fixed column positions .

When you open an existing file in ForReading mode, all existing data is overridden because the file pointer is automatically repositioned back to row 0 and column 0. On the other hand, if you open an existing file in ForAppending mode the file point is automatically placed at the end of the file.

To see how all this works, let's look at the following example. In this script, a file named Sample.txt is to be opened and a small text string written to it. The script begins by checking to see if the file already exists. If it does, then the file is opened in ForAppending mode. Otherwise, it is opened in ForWriting mode.

 //************************************************************ ************* //Script Name: Script 6.4.js //Author: Jerry Ford //Created: 09/14/03  //Description: This JScript demonstrates how to open a file //and then write data to it //************************************************************ ************* //Initialization Section   var fsoObject = new ActiveXObject("Scripting.FileSystemObject"); //Main Processing Section   //Determine what mode the output file should be opened in   if (fsoObject.FileExists("c:\MyDocs\Sample.txt")) {     var outputFile = fsoObject.OpenTextFile("c:\MyDocs\ Sample.txt", 8, "True")     AppendToFile()   } else {     var outputFile = fsoObject.OpenTextFile("c:\MyDocs\Sample.txt", 2, "True");     WriteToFile()   }   //Close the output file when done working with it   CloseFile()   //Terminate the script's execution   WScript.Quit(); //Procedure Section    function WriteToFile() {     outputFile.WriteLine(Date() + "  -  File opened in ForWriting Mode.");   }   function AppendToFile() {     outputFile.WriteLine(Date() + "  -  File opened in ForAppending mode.");   }   function CloseFile() {     outputFile.Close();   } 

The script begins by instantiating the FileSystemObject . Next, it uses the FileSystemObject object's FileExists property to determine whether or not a file named Sample.txt already exists in c:\MyDocs , as shown below. If it does exist, the AppendToFile() function is executed. Otherwise, the WriteToFile() function is called.

 //Determine what mode the output file should be opened in if (fsoObject.FileExists("c:\MyDocs\Sample.txt")) {   AppendToFile() } else {   WScript.Echo("The file does not exist") } 


This script assumes that the folder C:\MyDocs already exists. If it doesn't, an error will occur.Therefore, you might want to modify the script to verify that this folder exists as well.

The AppendToFile() function, shown below, uses the FileSystemObject object's OpenTextFile() method to set up a reference to C:\MyDocs\ Sample.txt . Note that the second parameter passed to OpenTextFile() is 8 , which tells the method to open the file in ForAppending mode. The FileSystemObject object's WriteLine() method is then executed. This method writes a text string to the file and performs a carriage return. I'll go over the use of this method in greater detail a little later in this chapter.

 function AppendToFile() {   outputFile.WriteLine(Date() + "  -  File opened in ForAppending mode."); } 

The WriteToFile() function, shown here, is very similar to the AppendToFile() function except that it opens the file in ForWriting mode, and an additional parameter with a value of True is passed to the OpenTextFile() that instructs the parameter to create the file if it does not already exist.

 function WriteToFile() {   outputFile.WriteLine(Date() + "  -  File opened in ForWriting Mode."); } 

Finally, the CloseFile() function is called, and the script terminates its own execution. This function uses the FileSystemObject object's CloseFile() method to close the file and write the end-of-file marker.

 function CloseFile() {   outputFile.Close(); } 


Always make sure that your JScripts close any open file before they stop executing. Failure to do so may result in an error the next time you try to access the file, because the end-of-file marker will be missing.

When you run this script for the first time, you should see a line of text similar to this:

 Sat Sep 20 06:08:58 2003  -  File opened in ForWriting Mode. 

Figure 6.7 shows how Sample.txt will look after running the script a few more times.

Figure 6.7. Creating a text file and appending new data to the end of it


[ LiB ]

Learn JavaScript In a Weekend
Learn JavaScript In a Weekend, Second Edition
ISBN: 159200086X
EAN: 2147483647
Year: 2003
Pages: 84 © 2008-2017.
If you may any questions please contact us: