Files
File Basics
Simple Files vs. File Objects
Whether you create an object or use the static methods, Jaxer creates a File object, so the key reason to use an object boils down to convenience.
If you'll only be calling one or two methods against the file then static is simpler; for more complex work create an object and store it in a
variable for reuse.
File Modes
When opening a file in Jaxer you pass a file mode to open to control how the the file will be accessed. The options for this are
show below. Use the binary mode strings when the data stored is not regular text; this is sometimes referred to as 'binary safe' file access.
Demonstrating the Different File Modes
// The following lines assume use of a File object called myfile
var myfile = new File('somefile.ext');
myfile.open('r'); // open for reading
myfile.open('w'); // open for writing, overwrites contents
myfile.open('a'); // open for appending data, new data is added to the file
myfile.open('rb'); // open binary file for reading
myfile.open('wb'); // open binary file for writing, overwrites contents
myfile.open('ab'); // open binary file for appending data, new data is added
Simple File Access
File Operations
Create
Use Jaxer.File.touch(path) to create a file if it doesn't exist and set the last modified timestamp if it does:
Jaxer.File.touch('myFile.txt');
Truncate
Use Jaxer.File.truncate(path) to empty the file of its current contents:
Jaxer.File.truncate('myfile.txt');
Delete
Jaxer.File.remove(path) deletes the file from the filesystem:
Jaxer.File.remove('myfile.txt');
Check for Existence
Use the Jaxer.File.exists(path) static method:
if (Jaxer.File.exists('myFile.txt'))
{
// myFile.txt exists
}
else
{
// myFile.txt does not exist
}
Copy
Jaxer.File.copy(source,destination) will copy the file to a new location, leaving the original file untouched. It will, however, overwrite the destination file if it exists and your application has sufficient privileges.
Jaxer.File.copy('myfile.txt','myfile.bak');
Move
Jaxer.File.move(source,destination) will move the file to a new location and the original file will be deleted. It will, however, overwrite the destination file if it exists and your application has sufficient privileges.
Jaxer.File.move('myfile.txt','myfile.bak');
Backup
Jaxer.File.backup(path) creates a uniquely named copy of the original file and returns the path to the newly created copy:
var backupFilePath = Jaxer.File.backup('myfile.txt');
File Attributes
Size
Jaxer.File.size(path) returns the size of the file in bytes:
var size = Jaxer.File.size('myfile.txt');
Extract parts of the filepath/name
- Filename portion of the path: Jaxer.File.filename(path)
- File extension: Jaxer.File.extension(path)
- Absolute path to the file: Jaxer.File.absolutePath(path)
- Path to the containing folder: Jaxer.File.parentPath(path)
var filename= Jaxer.File.filename('c:\\folder1\\folder2\\myfile.txt');
var filename= Jaxer.File.extension('c:\\folder1\\folder2\\myfile.txt');
var absolutePath = Jaxer.File.absolutePath('c:\\folder1\\folder2\\myfile.txt');
var parentPath = Jaxer.File.parentPath('c:\\folder1\\folder2\\myfile.txt');
Last Modified Date
Use Jaxer.File.dateModified(path):
var dateModified = Jaxer.File.dateModified('myfile.txt');
// returns 'Mon Mar 03 2008 19:13:17 GMT-0800 (Pacific Standard Time)'
Access Permissions
Jaxer.File.chmod(path,permissions) gets and sets file permissions; the path parameter is required, the permissions parameter is optional. Passing the permissions value is the setter, passing just a path is a getter. The permission value provided/returned is an octal number, in JavaScript this is a numeric literal with a leading 0.
Jaxer.File.chmod('myfile.txt',0400); // read only
var permissions = Jaxer.File.chmod('myfile.txt'); // -> '0400' (Windows: 0444)
CRC32 Checksum
Use Jaxer.File.checksum(path):
var checksum = Jaxer.File.checksum('myfile.txt');
File Content Operations
Get Contents
Jaxer.File.read(path) retreives the entire contents of the file into a JavaScript variable:
var contents = Jaxer.File.read('myFile.txt');
Append Content
Jaxer.File.append(path,content, content2, ..., contentN) will add the content to the end of the file and if the file doesn't exist it will be created.
Jaxer.File.append('myfile.txt','line1','line2');
Append a Line of Content
Jaxer.File.appendLine(path,content, content2, ..., contentN) will add the content to the end of the file, appending a new line after each passed content parameter, and if the file doesn't exist it will be created.
Jaxer.File.appendLine('myfile.txt','line1','line2');
Using File Objects
Creating a File Object
Create a new Jaxer.File(pathToFile) object; the parameter must include the full path to the referenced file system object or else the call will throw a 'NS_ERROR_FILE_UNRECOGNIZED_PATH' error. Note that creating a file object does not automatically create the equivalent object on the file system.
// use Jaxer.Dir.resolve(path) to avoid error
var filePath = Jaxer.Dir.resolve('myFile.txt');
var myFile = new Jaxer.File(filePath);
File Information
var isDir = myFile.isDir(); // false
var isFile = myFile.isFile(); // true
var isExec = myFile.isExec(); // false
var isSymlink = myFile.isSymlink(); // false
var isWritable = myFile.isWritable(); // true
var isReadable = myFile.isReadable(); // true
var isHidden = myFile.isHidden(); // false
var isSpecial = myFile.isSpecial(); // false
Managing Files
Create
Invoke the create() method on a file object:
var myFile = new Jaxer.File(Jaxer.Dir.resolve('myFile.txt'));
if (!myFile.exists())
{
myFile.create();
}
Delete
Use the remove() method. Once you delete the file, some methods previously available on the file object will throw exceptions if accessed.
// if the file exists delete it
if (!myFile.exists())
{
myFile.remove();
}
Truncate
Use truncate() to empty the file. After truncating, the file size will be zero bytes.
// if the file exists truncate it
if (!myFile.exists())
{
myFile.truncate();
}
Copy
The copy() method will copy the file to a provided file location; it throws an exception if the destination file already exists, which is different from the static file copy method's behavior.
if (myFile.exists() && myFile.isReadable())
{
var to = Jaxer.Dir.resolve('copy.txt');
myFile.copy(to);
to = Jaxer.Dir.combine(Jaxer.System.tempFolder,myFile.leaf);
myFile.copy(to);
}
File IO
Reading from Files
File Reading Setup
var readmePath = Jaxer.Dir.combine(Jaxer.System.executableFolder,'README-JAXER.TXT');
var readme = new Jaxer.File(readmePath);
Entire File
Read the entire contents of that file into a string, specifying the 'r' (read) access mode to the open method:
if (readme.exists() && readme.isReadable())
{
readme.open('r');
var contents = readme.read();
Jaxer.Log.info(contents);
readme.close();
}
Note: In a real application you would check that the file exists and is readable before opening it. Also, by default files are opened for read, so in this case, you could simple have omitted the access mode.
As an Array of Lines
The readAllLines() method returns the contents of a file as an array of individual lines. This method uses platform-specific line terminators when splitting the contents, and so is safer than using the String split('\n') method.
if (readme.exists() && readme.isReadable())
{
readme.open('r');
var contents = readme.readAllLines();
Jaxer.Log.info(contents.length);
readme.close();
}
One Character at a Time
The read() method takes a parameter representing the number of bytes to read from the file so to read the file one byte at a time, pass the value 1 to read() inside a loop until reaching file's end.
if (readme.exists() && readme.isReadable())
{
readme.open('r');
while ( ch = readme.read(1) )
{
Jaxer.Log.info(ch);
}
readme.close();
}
Writing to Files
Creating an Empty File
Use the create() method. This code will create an empty file named 'myFile.txt' in the same folder as the current page.
if (!myFile.exists())
{
myFile.create();
}
Appending Content
Appending to a file is done by opening a file in 'append mode' and writing data to that file; the 'a' parameter indicates the file should be opened in append mode.
if (myFile.exists() && myFile.isWritable())
{
myFile.open('a');
myFile.write("some text to write");
myFile.close();
}
Replacing the Content
Replace the contents of a file (or overwriting) by opening it in write mode, writing data to the file and closing it (this last step is important!).
if (myFile.exists() && myFile.isWritable())
{
myFile.open('w');
myFile.write("some text to write");
myFile.close();
}
Uploading Files
Uploading files to Jaxer from a web form is a straightforward process. All you need is a form containing an input element of type upload and an html page to receive the submitted form.
Receiving File Uploads
This code goes into the page which receives the data from the submitted form; the posted data is available within the Jaxer.request object.
We're specifically interested in Jaxer.Request.files, an array of Jaxer.Request.FileInfo objects, which has descriptive properties such as fileName, contentType and fileSize.
// outputs something similar to:
Saved to C:\aptana\JaxerDev\public\work\bar.txt
original filename : bar.txt
temp filename : C:\aptana\JaxerDev\tmp\tmp
contentType : text/plain
size : 15754
Saved to : C:\aptana\JaxerDev\public\work\foo.txt
original filename : foo.txt
temp filename : C:\aptana\JaxerDev\tmp\tmp-1
contentType : text/plain
size : 816
Downloading Files