Wholesale Application Community Device API Specifications 2.1

File System API

The File System API lets you manage files on the device.

Contents

  1. 1 Introduction
  2. 2 Virtual File System
    1. 2.1 Virtual Roots
    2. 2.2 Virtual Paths
    3. 2.3 Examples
  3. 3 Feature Strings
  4. 4 DeviceapisFSManagerinterface
  5. 5 FileSystemManager interface
    1. 5.1 The maxPathLength constant
    2. 5.2 The resolve() method
  6. 6 WACFile Interface
    1. 6.1 Example
    2. 6.2 The parent attribute
    3. 6.3 The readOnly attribute
    4. 6.4 The isFile attribute
    5. 6.5 The isDirectory attribute
    6. 6.6 The created attribute
    7. 6.7 The modified attribute
    8. 6.8 The path attribute
    9. 6.9 The name attribute
    10. 6.10 The fullPath attribute
    11. 6.11 The fileSize attribute
    12. 6.12 The length attribute
    13. 6.13 The toURI() method
    14. 6.14 The listFiles() method
    15. 6.15 The openStream() method
    16. 6.16 The readAsText() method
    17. 6.17 The copyTo() method
    18. 6.18 The moveTo() method
    19. 6.19 The createDirectory() method
    20. 6.20 The createFile() method
    21. 6.21 The resolve() method
    22. 6.22 The deleteDirectory() method
    23. 6.23 The deleteFile() method
  7. 7 FileFilter Dictionary
    1. 7.1 The name member
    2. 7.2 The startModified member
    3. 7.3 The endModified member
    4. 7.4 The startCreated member
    5. 7.5 The endCreated member
  8. 8 FileStream Interface
    1. 8.1 The eof attribute
    2. 8.2 The position attribute
    3. 8.3 The bytesAvailable attribute
    4. 8.4 The close() method
    5. 8.5 The read() method
    6. 8.6 The readBytes() method
    7. 8.7 The readBase64() method
    8. 8.8 The write() method
    9. 8.9 The writeBytes() method
    10. 8.10 The writeBase64() method
  9. Attributions
  10. Change Log

1 Introduction

The File System API provides access to specific locations on the file system of a device. The file system is represented as an abstract collection of disjointed virtual roots, each corresponding to a specific location on the device's file system.

2 Virtual File System

The File System API exposes limited parts of the operating system's file system using a virtual file system.

A virtual file system is an abstract layer that abstracts away some of the underlying structure of the real file system while also only allowing access to specific parts of the file system (know as virtual roots). The relationship of the virtual file system to the file system is illustrated in figure 1.

Virtual File System and Virtual Paths Removable storage widget package temporary folder widget package private space root documents root images root music root video roots downloads root widget package root virtual file system
The file system, the virtual file system, and the virtual roots.

Conceptually, the file system and the virtual file system consists of files and directories:

A file is a block of arbitrary information, or resource for storing information, which is available to a computer program and is usually based on some kind of durable storage. A file is durable in the sense that it remains available for programs to use after the current program has finished.

A directory is a virtual container within a  file system, in which groups of computer files and possibly other directories can be kept and organized. Files are kept organized by storing related files in the same directory. A directory contained inside another directory is called a subdirectory, while the containing folder is called the parent folder.

2.1 Virtual Roots

A virtual root is a case-senstive string representing a common location on the file system of a device (e.g., "downloads" is the default downloads folder of the system). It is the top-most folder that a widget can access in the virtual file system.

The virtual roots used by the File System API are as follows:

documents:
Represents the default folder in which text documents (e.g. pdf, doc...) are stored by default in the device. For example, in some platforms it corresponds to the "My Documents" folder.
images:

Represents the default folder in which still images such as pictures (e.g. jpg, gif, png, etc.) are stored by default in the device. For example, in some platforms it corresponds to the "My Images" folder.

music:

Represents the default folder in which sound clips (e.g. mp3 , aac, etc.) are stored by default in the device. For example, in some platforms it corresponds to the "My Music" folder.

videos:

Represents the default folder in which video clips (e.g. avi, mp4, etc.) are stored by default in the device. For example, in some platforms it corresponds to the "My Videos" folder.

downloads:

Represents the default folder in which downloaded files (e.g. by a browser, e-mail client, etc.) are stored by default in the device. For example, in some platforms it corresponds to the "Downloads" folder.

wgt-package:

Represents the readonly folder in which the content of the widget file was extracted to.

wgt-private:

Represents a private folder in which a widget can store information. This folder can only be accessed by the widget, other widgets or applications don't have access the information stored there.

wgt-private-tmp :

Represents a temporary, private folder in which a widget can store data that is available during one widget execution cycle. Content of this folder MAY be removed from this directory when the widget is closed or the Web Runtime is re-started. This folder is only accessible to the widget, other widgets or applications shouldn't have access to it.

removable:

Represents a folder that maps to the content stored on removable media such as an SD Card.

2.2 Virtual Paths

Each file or directory within the virtual file system is addressed using a virtual path. Together, viritual roots and virtual paths are formally described by the following ABNF:

virtual-path = virtual-path *file-name 
path         = virtual-root  *folder-name /
                 virtual-root  1*folder-name
folder-name  = file-name "/"
virtual-root = ("documents" / "images" / "music" / "videos"/ 
                 "downloads" / "wgt-private" / "wgt-package" / 
                 "wgt-private-tmp" / "removable")
file-name    = 1*allowed-char
allowed-char = safe-char / UTF8-char
UTF8-char    = UTF8-2 / UTF8-3 / UTF8-4
safe-char    = ALPHA  / DIGIT / SP  / "$" / "%" / 
                 "'"    / "-"   / "_" / "@" / "~" /
                 "("    / ")"   / "&" / "+" / "," /
                 "="    / "["   / "]" / "."
UTF8-2       = %xC2-DF UTF8-tail
UTF8-3       = %xE0 %xA0-BF UTF8-tail / %xE1-EC 2( UTF8-tail ) /
                 %xED %x80-9F UTF8-tail / %xEE-EF 2( UTF8-tail )
UTF8-4       = %xF0 %x90-BF 2( UTF8-tail ) / %xF1-F3 3( UTF8-tail ) /
                 %xF4 %x80-8F 2( UTF8-tail )
UTF8-tail    = %x80-BF
         

2.3 Examples

For example, a file is located at "My Music/coldplay/scientist.mp3", so the virtual path would be music/coldplay/scientist.mp3.

For example, a directory is located at Mi Musica/coldplay/, therefore, the virtual path is music/coldplay/.

For the special case of the root, if the root is music, then the virtual path is music.

3 Feature Strings

A file system feature declaration in a widget's configuration document represents a developer's intention to use the functionality provided by the File System API.

This API provides three feature strings that can be used by a developer. At least one needs to be present in a widget's configuration document in order for the API to be made available at runtime (subsequent repititions are ignored during processing). Which feature string is declared determines how the API behaves at runtime. The file system feature strings are as follows:

http://wacapps.net/api/file system.read

The following methods are disabled:

  • copyTo(),
  • createDirectory()
  • createFile()
  • moveTo()
  • deleteFile()
  • deleteDirectory()
  • openStream() with write mode ("w").
http://wacapps.net/api/file system.write

The following methods are disabled:

  • readAsText()
  • openStream() with read mode ("r").
http://wacapps.net/api/file system

The File System API behaves as defined in this specification.

4 DeviceapisFSManagerinterface

[NoInterfaceObject]
interface DeviceapisFSManager{
    readonly attribute FileSystemManager filesystem;
};
Deviceapis implements DeviceapisFSManager;

When a file system feature declaration appears in the widget's configuration document, the user agent implements the DeviceapisFSManager interface; thus providing access tothe File System API through the deviceapis.filesystem attribute (see FileSystemManager interface).

5 FileSystemManager interface

interface FileSystemManager {
    const unsigned long? maxPathLength;

    void resolve(Function successCallback,
           optional ErrorCB? errorCallback,
           DOMString location,
           [TreatUndefinedAs=Null] optional DOMString? mode);
};

The FileSystemManager interface provides a way to interface with the virtual file system. To avoid instantion of duplicate objects that represent the same file or directory, it is assumed that the user agent keeps a list of file instances.

5.1 The maxPathLength constant

The maxPathLength constant represents the maximum path length in bytes of the file system, if one is can be derived from the file system.

When getting the maxPathLength constant, the user agent MUST return the maximum path length in bytes of the file system (e.g., 1024). If the maximum path length cannot be derived, then return null.

Example

alert("The maximum path length is " + deviceapis.filesystem.maxPathLength);

5.2 The resolve() method

The resolve() method validates and resolves a path to a file in the virtual file system.

When invoked, the user agent MUST run the steps for resolving a file reference.

The steps for resolving a file reference

The steps for resolving a file reference are given by the following algorithm:

  1. Run the general invocation checks algorithm. If no exceptions were generated, continue asynchronously.

  2. If the operation completes successfully the handle is returned in the succesCallback. A valid location is prefixed with a valid root or default location and must address an existing, accessible file or directory.

The mode parameter specifies whether the resulting File object has read only access ("r" access) or read and write access ("rw" access) to the root location containing directory tree. Permission for the requested access is obtained from the security framework. Once the resulting File object has access, access is inherited by any other File objects derived from this instance without any further reference to the security framework, as noted in descriptions of certain methods of File.

Example

deviceapis.filesystem.resolve(
function(dir) {
	console.log("Mount point Name is " + dir.fullPath);
},
function(e) {
	console.log(e.message);
},
'images', 'r');

6 WACFile Interface

interface WACFile {
    readonly attribute WACFile?  parent;
    readonly attribute boolean   readOnly;
    readonly attribute boolean   isFile;
    readonly attribute boolean   isDirectory;
    readonly attribute Date?     created;
    readonly attribute Date?     modified;
    readonly attribute DOMString path;
    readonly attribute DOMString name;
    readonly attribute DOMString fullPath;
    readonly attribute long?     fileSize;
    readonly attribute long?     length;

    DOMString? toURI();

    void listFiles(Function successCallback,
                   optional ErrorCB? errorCallback,
                   optional FileFilter filter);

    void openStream(Function successCallback,
                    optional ErrorCB? errorCallback, 
                             DOMString mode,
        [TreatUndefinedAs=Null] optional DOMString? encoding);

    void readAsText(Function successCallback,
                                optional ErrorCB? errorCallback
        [TreatUndefinedAs=Null] optional DOMString? encoding);

    void copyTo(Function successCallback,
                ErrorCB? errorCallback,
                DOMString originFilePath,
                DOMString destinationFilePath,
                boolean overwrite);

    void moveTo(Function successCallback,
                            ErrorCB? errorCallback,
                            DOMString originFilePath,
                            DOMString destinationFilePath,
                            boolean overwrite);

    WACFile createDirectory(DOMString dirPath);

    WACFile createFile(DOMString filePath);

    WACFile resolve(DOMString filePath);

    deleteDirectory(Function successCallback,
                    optional ErrorCB? errorCallback
                    DOMString directory,
                    boolean recursive);

    deleteFile(Function successCallback,
                ErrorCallback errorCallback,  DOMString file);
  };

The WACFile interface is used to represent both files and directories. If permitted, a WACFile object can perform I/O operations such as reading and writing data from the virtual file system.

6.1 Example

function successCB(files) {
	for (var i = 0; i < files.length; i++) {
		console.log(files[i].fullPath + " size: " + files[i].fileSize);
	}
}

function errorCB(error) {
	console.log("The error " + error.message + " occurred when listing the files in the selected folder");
}

deviceapis.filesystem.resolve(
function(dir) {
	dir.listFiles(successCB, errorCB);
},
function(e) {
	console.log("Error" + e.message);
},
'documents', "rw");

6.2 The parent attribute

The parent attribute is a reference to the parent of this file or directory.

On getting, the user agent MUST return the an object that represents the parent of this file or directory.

Example

function successCB(files) {
	for (var i = 0; i < files.length; i++) {
		// alerts the file parent, should contain the
		// same value for all the files in the loop
		console.log("All the files should have the same parent: " + files[i].parent);
	}
}

function errorCB(error) {
	alert("The error " + error.message + " occurred when listing the files in the selected folder");
}

deviceapis.filesystem.resolve(
function(dir) {
	dir.listFiles(successCB, errorCB);
},
function(e) {
	alert("Error" + e.message);
},
'documents', "rw");

6.3 The readOnly attribute

The readOnly attribute represents the read/write system permission associated with the file.

On getting, the user agent MUST return true if the file permission is set to read-only, otherwise return false.

Example

function successCB(files) {
	for (var i = 0; i < files.length; i++) {
		if (files[i].readOnly) console.log("Cannot write to file " + files[i].name);
		else console.log("Can write to file " + files[i].name);
	}
}

function errorCB(error) {
	console.log("The error " + error.message + " occurred when listing the files in the selected folder");
}

deviceapis.filesystem.resolve(
function(dir) {
	dir.listFiles(successCB, errorCB);
},
function(e) {
	console.log("Error" + e.message);
},
'documents', "rw");

6.4 The isFile attribute

The isFile attribute can be used to determine if a File object is representing a file on the file system.

On getting, the user agent must return true if this handle is a file; otherwise, return false.

6.5 The isDirectory attribute

The isDirectory attribute can be used to determine if a File object is representing a directory on the file system.

On getting, the user agent must return true if this represents a directory; otherwise, return false.

6.6 The created attribute

The created attribute is a timestamp that represent when the file was first created in the file system.

On getting, if the user agent cannot determine the date on which the file was created, the user agent MUST return null. Otherwise, return a Date object that reflect the date and time on which the file was created as provided by the file system.

6.7 The modified attribute

The modified attribute is a timestamp that represents when the file was last changed on the file system.

On getting, if the user agent cannot determine the modified date from the operating system, the user agent MUST return null. Otherwise, return a Date object that reflect the date and time on which the file was modified as provided by the file system.

Example

alert(file.modified); // displays the modification timestamp

6.8 The path attribute

The path attribute represents the path componet of a virtual-path (excludes the filename component).

On getting, the user agent must return the path component of the virtual-path of the file that this object is representing.

Example

alert(file.path); // should be 'music/' if the file is music/foo.mp3

6.9 The name attribute

The name attribute represents the filename componet of a virtual-path.

On getting, if the user agent must run the steps to get the name of a file.

Steps to get the name of a file

The steps to get the name of a file are given by the following algorithm:

  1. If this WACFile object is representing a directory:

    1. Let name be the folder-name component of the virtual-path of this directory.

    2. From name, remove the 'SOLIDUS' (U+002F) character at the end of the string.

  2. Otherwise, the WACFile object is representing a file:

    1. Let name be file-name compoenent of the virtual-path of this file.

  3. Return name.

Example

alert(file.name); // should be foo.mp3 if the file path is music/foo.mp3

6.10 The fullPath attribute

The fullPath attribute represent the virtual path of the file this object is representing.

On getting, the user agent must return the virtual-path of the file that this object is representing.

Example

alert(file.fullPath); // should be music/track1.mp3 if the file is music/track1.mp3

6.11 The fileSize attribute

The fileSize attribute represents the size in bytes of a file.

When getting, if the WACFile object is representing a directory, then return null. Otherwise, return the size in bytes of a file.

Example

alert(file.fileSize); // displays the file size

6.12 The length attribute

The length attribute represents the number of files and directories contained by this WACFile object.

When getting, if the WACFile object is representing a file, then return null. Otherwise, return the size in bytes of a file. If the directroy is empty, return 0. Otherwise, return a count, starting from 1, of all the files and directories immidietely contained by this directory (do not recourse into subdirectories).

Example

alert(file.length); // '3' if the directory contains two files and one sub-directory

6.13 The toURI() method

Returns a URI that can be used to identify this entry. The URI has no specific expiration, it should be valid at least as long as the file exists.

When this method is invoked the implementation MUST generate a URI.

If that URI corresponds to any of the virtual roots (i.e. images, videos, music, documents, downloads and removable) the URI MUST be globally unique and could be used by any widget.

If that URI corresponds to a file located in any of the widget private areas (e.g. wgt-package, wgt-private, wgt-private-tmp). The generated URI MUST be unique for that file and for the widget making the request (e.g. including some derived from the widget id in the URI). The URI MUST be obfuscated so that it does not provide any information about the file location. These URIs MUST NOT be accessible to other widgets apart from the one invoking this method.

Example

// 'file://A123456ABCD/RockawayBeach.mp3' if the file is
// music/ramones/RockawayBeach.mp3
alert(file.toURI());

6.14 The listFiles() method

The listFiles() method, when invoked, returns a list of all files in a directory.

A file handle representing a directory can be used for listing all files and directories rooted as the file handle location.

The list of files will be passed as a array of files in the successCallback and contains directories and files. However, the directories "." and ".." MUST NOT be returned. Each File object part of the array MUST inherit all the access rights ("r" or "rw" mode) from the File object in which this method was invoked.

If the filter is passed and contains valid values, only those directories and files in the directory that match the filter criteria specified in the FileFilter interface MUST be returned in the successCallback. If no filter is passed, the filter is null or undefined, or contains invalid values, the implementation MUST return the full list of files in the directory.

If the directory does not contain any files or directories, or the filter criteria is unmatched to any files or directories, the successCallback will be invoked with an empty array.

Example

function successCB(files) {
	console.log("There are " + files.length + " in the selected folder");
}

function errorCB(error) {
	console.log("The error " + error.message + " occurred when listing the files in the selected folder");
}

deviceapis.filesystem.resolve(
function(dir) {
	dir.listFiles(successCB, errorCB)
},
function(e) {
	console.log("Error " + e.message);
},
"documents", "r");

6.15 The openStream() method

Opens the file in the given mode supporting the given encoding.

This operation is performed asynchronously. If the file is opened successfully, the successCallback is invoked with a FileStream that can be used for reading and writing the file, depending on the mode. The return FileStream instance includes a file pointer, which represents the current position in the file. The filepointer will by default be at the start of the file, except in the case of opening with append ("a") mode, in which case the filepointer points to the end of the file.

If the errorCallback does not contain a valid function (e.g. null) or in the case of any other error that should be returned in the errorCallback (see above), the implementation MUST silently fail and no further action is required (i.e. the error is not notified to the developer).

PendingOperation enabling the requester to cancel this request.

Example

function successCB(files) {
	for (var i = 0; files.length; i++) {
		console.log("File Name is " + files[i].name); // displays file name
	}

	var testFile = documentsDir.createFile("test.txt");
	if (testFile != null) {
		testFile.openStream(
		function(fs) {
			fs.write("HelloWorld");
			fs.close();
		},
		function(e) {
			console.log("Error " + e.message);
		},
		"w", "UTF-8");
	}
}

function errorCB(error) {
	console.log("The error " + error.message + " occurred when listing the files in the selected folder");
}

var documentsDir;
deviceapis.filesystem.resolve(
function(dir) {
	documentsDir = dir;
	dir.listFiles(successCB, errorCB);
},
function(e) {
	console.log("Error" + e.message);
},
'documents', "rw");

6.16 The readAsText() method

Reads the content of a file as a DOMString.

If the operation is successfully executed, the successCallback is invoked and a DOMString is passed as input parameter that represents the file content in the format determined by the encoding parameter.

If any of the input parameters are not compatible with the expected type for that parameter, a DOMException with the code TYPE_MISMATCH_ERR MUST be synchronously thrown.

If the errorCallback does not contain a valid function (e.g. null) or in the case of any other error that should be returned in the errorCallback (see above), the implementation MUST silently fail and no further action is required (i.e. the error is not notified to the developer).

PendingOperation enabling the requester to cancel this request.

Example

var documentsDir;

function successCB(files) {
	for (var i = 0; files.length; i++) {
		if (files[i].isDirectory) {
			continue;
		}
		console.log("File Name is " + files[i].name);
		files[i].readAsText(function(str) {
			console.log("The file content " + str);
		},
		function(e) {
			console.log("Error " + e.message);
		},
		"UTF-8");
	}
}

function errorCB(error) {
	console.log("The error " + error.message);
}

deviceapis.filesystem.resolve(
function(dir) {
	documentsDir = dir;
	dir.listFiles(successCB, errorCB);
},
function(e) {
	console.log("Error" + e.message);
},
'documents', "rw");

6.17 The copyTo() method

Copies (and overwrites if possible and specified) a file or a directory from a specified location to another specified location.

The copy of the file or directory identified by the originFilePath parameter MUST be created in the path passed in the destinationFilePath parameter.

The file or directory to be copied MUST be under the Directory from which the method is invoked, otherwise the operation MUST NOT be performed.

If the copy is performed successfully, the successCallback is invoked.

If the errorCallback does not contain a valid function (e.g. null) or in the case of any other error that should be returned in the errorCallback (see above), the implementation MUST silently fail and no further action is required (i.e. the error is not notified to the developer).

PendingOperation enabling the requester to cancel this request.

Example

var documentsDir;
var newDir;

function copyTo() {
	console.log("file copied");
}

function copyError(error) {
	console.log("Copy error " + error.message + " occurred");
}

function listError(error) {
	console.log("List error " + error.message + " occurred");
}

function successCB(files) {
	for (var i = 0; i < files.length; i++) {
		if (files[i].isDirectory) {
			continue;
		}
		console.log('Attempting copy: ' + files[i].fullPath + ' -> documents/barfoo/' + files[i].name);
		documentsDir.copyTo(copyTo, copyError, files[i].fullPath, "documents/barfoo/" + files[i].name, true);
	}
}

deviceapis.filesystem.resolve(
function(dir) {
	documentsDir = dir;
	newDir = dir.createDirectory("barfoo");
	dir.listFiles(successCB, listError);
},
function(e) {
	console.log("Error" + e.message);
},
'documents', "rw");

6.18 The moveTo() method

Moves a file or a directory from a specified location to another.

The file or directory will be moved (and will overwrite if possible and specified) atomically to the given path. This operation is different to instantiating copyTo and then deleting the original file, as on certain platforms, this operation does not require extra disk space.

The file or directory identified by the originFilePath parameter MUST be moved to the path passed in the destinationFilePath parameter.

The file to be moved MUST be under the Directory from which the method is invoked, otherwise the operation MUST NOT be performed.

If the file or directory is moved successfully, the successCallback is invoked.

If the errorCallback does not contain a valid function (e.g. null), or in the case of any error that should be returned in the errorCallback (see above), the implementation MUST silently fail and no further action is required (i.e. the error is not notified to the developer).

Example

var documentsDir;
var newDir;

function moveTo() {
	console.log("file moved");
}

function moveError(error) {
	console.log("move error " + error.message + " occurred");
}

function listError(error) {
	console.log("List error " + error.message + " occurred");
}

function successCB(files) {
	for (var i = 0; i < files.length; i++) {
		if (files[i].isDirectory) {
			continue;
		}
		console.log('Attempting move: ' + files[i].fullPath + ' -> documents/barfoo/' + files[i].name);
		documentsDir.moveTo(moveTo, moveError, files[i].fullPath, "documents/barfoo/" + files[i].name, true);
	}
}

deviceapis.filesystem.resolve(
function(dir) {
	documentsDir = dir;
	newDir = dir.createDirectory("barfoo");
	dir.listFiles(successCB, listError);
},
function(e) {
	console.log("Error" + e.message);
},
'documents', "rw");

6.19 The createDirectory() method

The createDirectory() method, when invoked, attempts to creates a subdirectory. This operation can only be performed on objects that represent a directory.

A new directory will be created relative to the current directory that this operation is performed on. The implementation will attempt to create all necessary sub-directories specified in the dirPath as well. The use of "." or ".." in path components is not supported.

The file handle of the new directory. The new File object will have "rw" access rights, as it inherits this from the File object on which the createDirectory() method is called.

Example

 var newDir = dir.createDirectory("newDir");
 var anotherNewDir = dir.createDirectory("newDir1/subNewDir1"); 

6.20 The createFile() method

The createFile() method, when invoked, attempts to create a new empty file at a specified virtual path. This operation can only be performed with a file object that represent a directory.

A new empty file is created in the given path relative to the current directory the operation is performed on. The use of "." or ".." in path components is not supported.

If the file is successfully created, a File handler MUST be returned by this method.

The file handle of the new empty file. The new File object will have "rw" access rights, as it inherits this from the File object on which the createFile() method is called.

Example

var newFile = dir.createFile("newFilePath"); 

6.21 The resolve() method

Resolves an existing file or directory relative to the current directory this operation is performed on; and returns a file handle for it.

The filePath is not allowed to contain the "." or ".." directories.

The encoding of file paths is UTF-8.

Example

var file;
// Resolves helloWorld.doc file that is located in the
// documents root location
deviceapis.filesystem.resolve(
function(dir) {
	file = dir.resolve("helloWorld.doc");
},
function(e) {
	alert("Error" + e.message);
},
'documents', "rw");

6.22 The deleteDirectory() method

The deleteDirectory() method, when invoked, asynchronoulsy attempts to delete a specified directory and directory tree if specified.

If the recursive parameter is set to true, all the directories and files under the specified directory MUST be deleted. If the recursive parameter is set to false, the directory will only be deleted if it is empty, otherwise an IO_ERR error code will be passed in errorCallback.

The directory to be deleted MUST be under the Directory that the method is invoked from, otherwise the operation MUST NOT be performed. If the deletion is performed successfully, the successCallback is invoked.

If the errorCallback does not contain a valid function (e.g. null), or in the case of any other error that should be returned in the errorCallback (see above), the implementation MUST silently fail and no further action is required (i.e. the error is not notified to the developer).

Example

var documentsDir;

function deleted(file) {
	console.log(file + " deleted");
}

function error(e) {
	console.log("Error" + e.message);
}

function successCB(files) {
	for (var i = 0; files.length; i++) {
		if (!confirm('Delete ' + files[i].fullPath + ' ?')) {
			continue;
		}
		if (files[i].isDirectory) {
			documentsDir.deleteDirectory(deleted(files[i].fullPath), error, files[i].fullPath, false);
		} else {
			documentsDir.deleteFile(deleted(files[i].fullPath), error, files[i].fullPath);
		}
	}
}

deviceapis.filesystem.resolve(function(dir) {
	documentsDir = dir;
	dir.listFiles(successCB, error);
},
error, 'documents', 'rw');

6.23 The deleteFile() method

This function attempts to asynchronously delete a file under the current directory.

The file to be deleted MUST be under the Directory from which the method is invoked, otherwise the operation MUST NOT be performed.

If the deletion is performed successfully, the successCallback is invoked.

If the errorCallback does not contain a valid function (e.g. null), or in the case of any error that should be returned in the errorCallback (see above), the implementation MUST silently fail and no further action is required (i.e. the error is not notified to the developer).

7 FileFilter Dictionary

dictionary FileFilter {    
  DOMString name;
  Date startModified;
  Date endModified;
  Date startCreated;
  Date endCreated;
};

Object created to filter the items returned by the listFiles method.

When this object is passed in the listFiles method, the result-set of the listFiles method MUST only contain the File items entries that match the attribute values of the filter.

A File item only matches the FileFilter object if all the attributes of the File item match all the attribute values of the filter which are defined (i.e. only matching values other than undefined or null). This is similar to an SQL "AND" operation.

An attribute of the File entry matches the FileFilter attribute value in accordance with the following rules:

7.1 The name member

The name member is used for filtering the file-name attribute.

Files which name corresponds with this attribute (either exactly or with the specified wildcards) match this filtering criteria.

7.2 The startModified member

The startModified member can be used to filter on a file's last modified date.

Files with modified date later than this attribute or equal to it match the filtering criteria.

7.3 The endModified member

The endModified member is used to filter the on the date on wich files were created on the file system.

Files with modified date earlier than this attribute or equal to it match the filtering criteria.

7.4 The startCreated member

Used for filtering the File created attribute.

Files with created date later than this attribute or equal to it match the filtering criteria.

7.5 The endCreated member

Used for filtering the File created attribute.

Files with created date earlier than this attribute or equal to it match the filtering criteria.

8 FileStream Interface

interface WACFileStream {
    readonly attribute boolean eof;
             attribute long position set;
    readonly attribute long bytesAvailable;

    void close();
    DOMString read(long charCount);
    octet[] readBytes(long byteCount);
    DOMString readBase64(long byteCount);
    void write(DOMString stringData);
    void writeBytes(octet[] byteData);
    void writeBase64(DOMString base64Data);
  };

A FileStream represents a handle to a File opened for read and/or write operations. Read and write operations are performed relative to a position attribute which is a pointer that represents the current position in the file.

A series of read/write methods are available that permit both binary and text to be processed.

Once a file stream is closed, any operation attempted on this stream will result in a standard JavaScript error.

The read/write operations in this interface do not throw any security exceptions as the access rights are expected to be granted through the initial resolve() method or through the openStream() method of the File interface. Therefore, all actions performed on a successfully resolved File and FileStream are expected to succeed. This avoids succesive asynchronous calls and may potentially increase application for a user.

8.1 The eof attribute

The eof attribute indicates whether or not the current file pointer is at the end of the file.

If true this attribute indicates that the file pointer is at the end of the file.

If false this attribute indicates that the file pointer is not at the end of the file and maybe anywhere within the file.

Example

 if(stream.eof) {
   // file has been read completely
 } 

8.2 The position attribute

The position attribute represents an offset of bytes from the start of the file stream. When invoking an operation that reads or writes from the stream, the operation will take place from the byte defined by this position attribute. If the read or write operation is successful, the position of the stream is advanced by the number of bytes read. If the read/write operation is not successful the position of the stream is unchanged.

Example

alert(stream.position); // displays current stream position
// alters current stream position to the begin of the file,
// like seek() in C
stream.position = 0;

8.3 The bytesAvailable attribute

The bytesAvailable attribute returns the number of bytes that are available for reading from the stream.

The number of bytes available for reading is the maximum amount of bytes that can be read in the next read operation. It corresponds to the number of bytes available after the file pointer denoted by the position attribute.

-1 if eof is true.

Example

// displays the available bytes to be read
alert(stream.bytesAvailable);

8.4 The close() method

The close() method closes this FileStream.

Flushes any pending buffered writes and closes the File. Always succeeds. Note that pending writes might not succeed.

Example

// closes this stream, no subsequent access to stream allowed
stream.close();

8.5 The read() method

The read() method reads the specified number of characters from this FileStream.

Reads specified number of characters after the position file pointer and returns them as string. The resulting string length might be shorter than charCount if eof is true.

Example

var text = stream.read(file.fileSize);
stream.close();

8.6 The readBytes() method

The readBytes() method reads the specified number of bytes from this FileStream.

Example

// reads up to 256 bytes from the stream
var raw = stream.readBytes(256);
for (var i = 0; i < raw.length; i++) {
	// raw[i] contains the i-th byte of the current data chunk
}

8.7 The readBase64() method

The readBase64() method Reads the specified number of bytes from this FileStream, encoding the result in base64.

Example

// reads up to 256 bytes from the stream
var base64 = stream.readBase64(256);

8.8 The write() method

The write() method writes the specified DOMString to this FileStream.

Example

var text = "Hello world";
stream.write(text);

8.9 The writeBytes() method

The writeBytes() method writes the specified bytes to this FileStream.

Example

var bytes = in .readBytes(256);
out.writeBytes(bytes); // writes the bytes read from in to out

8.10 The writeBase64() method

The writeBase64() method converts a specified base64 DOMString to bytes and writes the result to this FileStream.

Example

var base64 = in.readBase64(256);
out.writeBase64(base64); // writes the base64 data read from in to out

Attributions

This article uses material from the Wikipedia article Computer File, File System, and Folder (computing), which are released under the Creative Commons Attribution-Share-Alike License 3.0.

Change Log

This specification was last updated on 30 April 2012. A complete list of changes are kept on our GIT repository.