Bondi logo

The BONDI filesystem Module - Version 1.1

9 February 2010

Authors


Abstract

BONDI filesystem API.

Table of Contents


Summary of Methods

InterfaceMethod
FileSystemSuccessCallbackvoid onSuccess(File file)
FileSystemManagerDOMString getDefaultLocation(DOMString specifier, unsigned long minFreeSpace)
StringArray getRootLocations()
PendingOperation resolve(FileSystemSuccessCallback successCallback, ErrorCallback errorCallback, DOMString location, DOMString mode)
void registerEventListener(FileSystemListener listener)
void unregisterEventListener(FileSystemListener listener)
FileSystemListenervoid mountEvent(DOMString location)
void unmountEvent(DOMString location)
FileFileArray listFiles()
FileStream open(DOMString mode, DOMString encoding)
PendingOperation copyTo(FileSystemSuccessCallback successCallback, ErrorCallback errorCallback, DOMString filePath, boolean overwrite)
PendingOperation moveTo(FileSystemSuccessCallback successCallback, ErrorCallback errorCallback, DOMString filePath, boolean overwrite)
File createDirectory(DOMString dirPath)
File createFile(DOMString filePath)
File resolve(DOMString filePath)
PendingOperation deleteDirectory(FileSystemSuccessCallback successCallback, ErrorCallback errorCallback, boolean recursive)
boolean deleteFile()
FileStreamvoid close()
DOMString read(unsigned long charCount)
ByteArray readBytes(unsigned long byteCount)
DOMString readBase64(unsigned long byteCount)
void write(DOMString stringData)
void writeBytes(ByteArray byteData)
void writeBase64(DOMString base64Data)
FileSystemManagerObject

1. Introduction

The BONDI filesystem API provides access to the filesystem of a device. The filesystem is abstractly represented as a collection of disjoint filesystem root locations each corresponding to some specific location in the device filesystem. The filesystem API exposes the hierarchies below these root locations as a single virtual filesystem but provides no access to other parts of the device filesystem.

The roots that are exposed are determined by the platform also by the context in which the filesystem API is invoked.

Each root has a string name. Each file or directory within the virtual filesystem is addressed using a fully-qualified path of the form: <root name>/<path> where <rootname> is the name of the root and <path> is the path to the file or directory relative to that root.

The list of the supported root locations can be retrieved by calling filesystem.getRootLocations().

The default location for a specific type of file, if one exists, can be obtained by calling the filesystem.getDefaultLocation(...) method. A set of platform-independent symbolic names for media types is defined. The default location for a given file type may itself be a root, or some subdirectory of a root. Although the set of roots available on a device is platform-dependent, the getDefaultLocation(...) functionality can be used to ensure that web applications can be written in a platform-independent way.

In order to access specific locations which are prefixed with a value retrieved by filesystem.getDefaultLocation or some root location returned by filesystem.getRootLocations a File handle must be retrieved using the filesystem.resolve call.

A File handle represents either a file or a directory. If it is a file the isFile attribute will be true, otherwise the isDirectory attribute will be true. A file can be opened for reading and writing, using a FileStream handle. A directory can be used to list its contents which is a list of files and sub-directories. There is a resolve method on directories as well in order to resolve files or sub-directories more conveniently than processing directory listings.

The "/" character is used as the (path) component separator. The use of "." or ".." in location components is not required to be supported.

All path characters need to be UTF-8 encoded.

1.1. Feature set

This is the URI used to declare this API's feature set, for use in bondi.requestFeature. For the URL, the list of features included by the feature set is provided.

http://bondi.omtp.org/api/1.1/filesystem

All the FileSystem features

Includes API features:

  • http://bondi.omtp.org/api/1.1/filesystem.read
  • http://bondi.omtp.org/api/1.1/filesystem.write

1.2. Features

This is the list of URIs used to declare this API's features, for use in bondi.requestFeature. For each URL, the list of functions covered is provided.

When any of the features

is successfully requested, the interface FileSystemManager is instantiated, and the resulting object appears in the global namespace as Bondi.filesystem.

http://bondi.omtp.org/api/1.1/filesystem.read

Filesystem read operations, including reading directory listings, file metadata, file contents and resolving root locations. This permission is obtained during a call to FileSystemManager.resolve(), allowing read access to any part of the file system reachable from the returned File object.

Device capabilities:

  • io.file.read
http://bondi.omtp.org/api/1.1/filesystem.write

Filesystem write operations, including creating files/directories, writing to files, deleting files/directories, moving and copying files. This permission is obtained during a call to FileSystemManager.resolve(), allowing write access to any part of the file system reachable from the returned File object, if read-write access is requested. It is also obtained for the destination file in File.moveTo and File.copyTo where the root location of the destination is different from that of the source or the source File object does not have read-write access.

Device capabilities:

  • io.file.write

1.3. Device capabilities

io.file.read

Filesystem read operations, including reading directory listings, file metadata, file contents and resolving root locations.

Security parameters:

  • name: The root location prefix of the filename (without trailing slash).
io.file.write

Open and write files and creating directories

Security parameters:

  • name: The root location prefix of the filename (without trailing slash).

2. Type Definitions

2.1. FileArray

Array of File handles.

        typedef sequence<File> FileArray;

This array type is returned when directory listings are requested.

3. Interfaces

3.1. FileSystemSuccessCallback

File system specific success callback.

        [Callback=FunctionOnly, NoInterfaceObject] interface FileSystemSuccessCallback {
                void onSuccess(in File file);
        };

This callback interface specifies a success callback with a function taking a File object as input argument. It is used in asynchronous operations such as FileSystemManager.resolve(), and copying, moving and deleting files.

Methods

onSuccess

Method invoked when the asynchronous call completes successfully

Signature
void onSuccess(in File file);
Parameters
  • file: The file resulting from the asynchronous call

3.2. FileSystemManager

Manager class exposed as the filesystem modules API.

        interface FileSystemManager {

                readonly attribute unsigned long maxPathLength;

                DOMString getDefaultLocation(in DOMString specifier, in unsigned long minFreeSpace)
                        raises(DeviceAPIError);

                StringArray getRootLocations();

                PendingOperation resolve(in FileSystemSuccessCallback successCallback,
                                in ErrorCallback errorCallback,
                                in DOMString location,
                                [Optional] in DOMString mode);

                void registerEventListener(in FileSystemListener listener)
                        raises(DeviceAPIError);

                void unregisterEventListener(in FileSystemListener listener)
                        raises(DeviceAPIError);
        };

This manager class exposes the filesystem base API, such as determining root and default locations, resolving a given location into a File Handle and registering filesystem listeners for filesystem events.

Code example
                var docLocation = bondi.filesystem.getDefaultLocation("documents");
                var docDir = bondi.filesystem.resolve(docLocation);
                var docFiles = docDir.listFiles();
                for(var i = 0; i < docFiles.length; i++) {
                        // displays name of each image file in image directory
                        alert(docFiles[i].name);
                }
                var testFile = docDir.createFile("test.txt");
                var out = testFile.open("w", "UTF-8");
                // writes Hello World to test.txt
                out.write("Hello World");
                out.close();
 

Attributes

readonly unsigned long maxPathLength

Contains the platform-dependent maximum path length.

Read-only.

Code example
        alert(bondi.filesystem.maxPathLength);
 

Methods

getDefaultLocation

Returns a default location path for the given arguments, including the root location prefix.

Signature
DOMString getDefaultLocation(in DOMString specifier, in unsigned long minFreeSpace);

Optionally this method can be called with the space argument specifying the minimum free disk space required.

This function resolves location specifiers to location paths. The following location specifiers are supported:
"wgt-package" the widget package location
"wgt-private" the widgets private storage
"wgt-public" the widgets public storage
"wgt-temp" the widgets temporary storage
"documents" the documents location, e.g. the "My Documents" directory on some systems
"images" the images location, e.g. the "My Pictures" directory on some systems
"videos" the videos location, e.g. the "My Videos" directory on some systems
"temp" the temporary storage, e.g resolving to "Temp"
"sdcard" the sdcard storage, if any

Parameters
  • specifier: the location specifier, see above for supported specifiers.
  • minFreeSpace: optional, minimum required free disk space in bytes for this location, 0 (default) means no limitation
Return value
the location as a string or null if there is no location for the given specifier or if there is not enough space left for the requested space in bytes.
Exceptions
  • DeviceAPIError:

    INVALID_ARGUMENT_ERROR if the specifier or space arguments are invalid

Code example
        var wgtLocation = bondi.filesystem.getDefaultLocation('wgt-package');
 
getRootLocations

Returns all root locations.

Signature
StringArray getRootLocations();

The root locations are symbolic names for filesystem locations which are accessible and supported by the underlying platform.

Usually the following root locations will be supported:
"documents" represents "My Documents" on some platforms
"images" represents "My Pictures" on some platforms
"videos" represents "My Videos" on some platforms
"temp" represents "tmp" on some platforms
"sdcard" represents the sdcard on some platforms

See also the getDefaultLocation method.

Return value
string array of root locations.
Code example
        var locations = bondi.filesystem.getRootLocations();
        for(var i = 0; i < locations.length; i++) {
                // locations[i] is a resolvable root location
        }
 
resolve

Resolves a location to a File handle.

Signature
PendingOperation resolve(in FileSystemSuccessCallback successCallback, in ErrorCallback errorCallback, in DOMString location, in DOMString mode);

Validates and resolves the given location to a File handle and returns a handle. A valid location is prefixed with a valid root or default location and must address an existing and accessible file or directory.

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

Errors that may be returned in the ErrorCallback:

  • SecurityError PERMISSION_DENIED_ERROR when access is denied by the security policy.
  • DeviceAPIError INVALID_ARGUMENT_ERROR if invalid location or invalid mode was given.
Parameters
  • successCallback: called when the location has been successfully resolved, passing the newly created File object.
  • errorCallback: called if an error occurred.
  • location: the location to resolve. Must be absolute, prefixed by a valid root or default location.
  • mode: optional string of value "r" to obtain only read access or "rw" to obtain read and write access to all files and directories that can be reached from the File object passed to successCallback. Defaults to "rw" if absent.
Return value
PendingOperation enabling the requester to cancel this request.
API features
http://bondi.omtp.org/api/1.1/filesystem.read
http://bondi.omtp.org/api/1.1/filesystem.write
(only if mode parameter is omitted or "rw")
Code example
        var location = bondi.filesystem.getDefaultLocation("temp");
        var temp = bondi.filesystem.resolve(location);
        var documents = bondi.filesystem.getDefaultLocation("documents");
        var mydoc = bondi.filesystem.resolve(documents + "/data/2009/mydoc.txt");
 
registerEventListener

Registers a filesystem event listener.

Signature
void registerEventListener(in FileSystemListener listener);

Filesystem event listeners are used in order to retrieve notifications if root or default locations such as storage cards are mounted/unmounted into/from the device filesystem.

Parameters
  • listener: the listener interface implementation
Exceptions
  • DeviceAPIError:

    INVALID_ARGUMENT_ERROR if the given listener is invalid or not a listener.

Code example
        var listener = { mountEvent: function(location) { alert('mounted ' + location); },
                         unmountEvent: function(location) { alert('unmounted ' + location); };
        bondi.filesystem.registerEventListener(listener);
 
unregisterEventListener

Unregisters a filesystem event listener.

Signature
void unregisterEventListener(in FileSystemListener listener);
Parameters
  • listener: the listener interface implementation
Exceptions
  • DeviceAPIError:

    INVALID_ARGUMENT_ERROR if the given listener is invalid or not a listener.

Code example
        bondi.filesystem.unregisterEventListener(listener);
 

3.3. FileSystemListener

Filesystem event listener class.

        interface FileSystemListener {

                void mountEvent(in DOMString location);

                void unmountEvent(in DOMString location);
        };

This listener implements two methods to retrieve mount and unmount notifications if root or default locations on a storage card get available or unavailable.

Code example
        var fsEventImpl = {
                mountEvent: function(location) {
                        // location has been mounted
                },
                unmountEvent: function(location) {
                        // location has been unmounted
                }
        };
 

Methods

mountEvent

Called when a new root location gets available.

Signature
void mountEvent(in DOMString location);

A new location could be a storage card for example.

Parameters
  • location: the newly available location
unmountEvent

Called when a location gets unavailable.

Signature
void unmountEvent(in DOMString location);

Such a location could be a storage card for example.

Parameters
  • location: the location which is becoming unavailable

3.4. File

File class.

        interface File {

                readonly attribute File 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 absolutePath;

                readonly attribute unsigned long fileSize;

                readonly attribute Map metadata;

                FileArray listFiles()
                        raises(SecurityError, DeviceAPIError);

                FileStream open(in DOMString mode, in DOMString encoding)
                        raises(SecurityError, DeviceAPIError);

                PendingOperation copyTo(in FileSystemSuccessCallback successCallback,
                                in ErrorCallback errorCallback,
                                in DOMString filePath,
                                in boolean overwrite);

                PendingOperation moveTo(in FileSystemSuccessCallback successCallback,
                                in ErrorCallback errorCallback,
                                in DOMString filePath,
                                in boolean overwrite);

                File createDirectory(in DOMString dirPath)
                        raises(SecurityError, DeviceAPIError);

                File createFile(in DOMString filePath)
                        raises(SecurityError, DeviceAPIError);

                File resolve(in DOMString filePath)
                        raises(SecurityError, DeviceAPIError);

                PendingOperation deleteDirectory(in FileSystemSuccessCallback successCallback,
                                                 in ErrorCallback errorCallback,
                                                 in boolean recursive);
                        

                boolean deleteFile()
                        raises(SecurityError, DeviceAPIError);
        };

This interface represents the file abstraction in use. A file handle can address files or directories. A file handle represents a file if the isFile property is true, otherwise it represents a directory.

A File object has just read access ("r" access) or full read-write access ("rw" access) to the root location containing its location and the whole tree rooted there. When a File object is used to create another File object, the new File object inherits its access rights from the original one without any reference to the security framework, as noted in certain methods of File.

A file handle representing a file can be opened for I/O operations such as reading and writing.

A file handle representing a directory can list all files in the current directory.

Code example
        // list directory contents
        var files = dir.listFiles();
        for(var i = 0; i < files.length; i++) {
                // alerts each name of dir's contents
                alert(files[i].name);
        }

        // opens a file for writing
        var file = dir.createFile("test.txt");
        var out  = file.open("w", "UTF-8");
        // writes Hello World to test.txt
        out.write("Hello World");
        out.close();
 

Attributes

readonly File parent

Parent directory handle.

Read-only.

null if there is no parent directory.

If there is no parent directory, this represents a root location.

Code example
        var parent = file.parent;
        if(parent != null) {
                // parent directory handle
        }
 
readonly boolean readOnly

File/directory access state in the filesystem.

Read-only.

false if there is write access.

This attribute represents the actual state of a file/directory in the filesystem. Its value is not affected by the mode used in the FileSystemManager.resolve that was used to create the File object from which this File object was obtained.

Code example
        if(file.readOnly) {
                // file cannot be written
        }
 
readonly boolean isFile

File type.

Read-only.

true if this handle is a file. false if this handle is a directory.

Code example
        if(file.isFile) {
                // is a file
        }
 
readonly boolean isDirectory

File type.

Read-only.

true if this handle is a directory. false if this handle is a file.

Code example
        if(file.isDirectory) {
                // is a directory
        }
 
readonly Date created

Creation timestamp.

Read-only.

The creation timestamp of this file. This is the timestamp when the file was first created in the filesystem. This is equivalent to the timestamp when a call to createFile() succeeds.

It is unspecified and platform-dependent if the creation timestamp changes when a file is moved.

Code example
        alert(file.created); // displays the creation timestamp
 
readonly Date modified

Modification timestamp.

Read-only.

The modification timestamp of this file. This is the timestamp of the most recent modification to the file, usually when the last write operation succeeded. Opening a file for reading does not change the modification timestamp.

Code example
        alert(file.modified); // displays the modification timestamp
 
readonly DOMString path

Path of this file, excluding the file name.

Read-only.

If the file path is /baz/foo.bar, then the path is /baz/.

The encoding of file paths is UTF-8.

Code example
        alert(file.path); // should be /baz/ if the file is /baz/foo.bar
 
readonly DOMString name

File name, excluding any path components.

Read-only.

Assumed the file path is /baz/foo.bar, then the file name is foo.bar.

The encoding of file names is UTF-8.

Code example
        alert(file.name); // should be foo.bar if the file path is /baz/foo.bar
 
readonly DOMString absolutePath

Absolute path of this file.

Read-only.

Assumed the file path is /baz/foo.bar, then this is the absolute path.

The encoding of file paths is UTF-8.

Code example
        alert(file.absolutePath); // should be /baz/foo.bar if the file is /baz/foo.bar
 
readonly unsigned long fileSize

Size in bytes of this file.

Read-only.

If it is attempted to read this attribute on a directory, undefined is returned.

Code example
        alert(file.fileSize); // displays the file size
 
readonly Map metadata

Files metadata.

The actual map contents are implementation dependent.

Code example
        // should display the file author, if supported by the
        // platform, undefined otherwise
        alert(file.metadata.author);
 

Methods

listFiles

Returns list of all files of this directory.

Signature
FileArray listFiles();

The list of files contains directories and files, it does not contain the directories "." and "..".

Return value
array of contents of this directory. Each File object in the array inherits its access rights ("r" or "rw") from the File object on which listFiles was called.
Exceptions
  • SecurityError:
  • DeviceAPIError:

    IO_ERROR if this is not a directory.

Code example
        var files = dir.listFiles();
        for(var i = 0; i < files.length; i++) {
                // files[i] iterate over all files of this directory
        }
 
open

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

Signature
FileStream open(in DOMString mode, in DOMString encoding);
Parameters
  • mode: the mode for opening a file
    "r" for reading
    "a" for appending
    "w" for [over]writing
  • encoding: the encoding for read/write operations on the file, supported encodings are:
    "UTF-8" default encoding
    "ISO8859-1" latin1 encoding
Return value
file stream handle to read/write from/to.
Exceptions
  • SecurityError:

    PERMISSION_DENIED_ERROR when appending or writing is requested for a File which has only "r" access rather than full "rw" access.

  • DeviceAPIError:

    IO_ERROR if this is not a file.

    INVALID_ARGUMENT_ERROR if invalid mode or unsupported encoding is supplied.

Code example
        // opens file for reading
        var in = file.open("r", "UTF-8");
 
copyTo

Copies this file.

Signature
PendingOperation copyTo(in FileSystemSuccessCallback successCallback, in ErrorCallback errorCallback, in DOMString filePath, in boolean overwrite);

The copy will be created in the given path. If this function fails and the error callback is called, it will pass an DeviceAPIError IO_ERROR to the callback.

The encoding of file paths is UTF-8.

Errors that may be returned in the ErrorCallback:

  • SecurityError PERMISSION_DENIED_ERROR when access is denied by the security policy.
  • DeviceAPIError IO_ERROR if it is attempted to copy to a directory.
  • DeviceAPIError IO_ERROR if overwrite is false and target file exists.
  • DeviceAPIError IO_ERROR if any characters in the path are not supported.
  • DeviceAPIError IO_ERROR if the file cannot be copied.
Parameters
  • successCallback: called when the file has been copied.
  • errorCallback: called if an error occurred.
  • filePath: the new file path, [a-Z0-9_- /]+ are allowed
  • overwrite: true enforces overwriting an existing file.
Return value
PendingOperation enabling the requester to cancel this request.
API features
http://bondi.omtp.org/api/1.1/filesystem.write
is obtained for the destination's root location, only if that is different from the source file's root location, or if this File object does not have full "rw" access rights.
Code example
        // copies this file to /temp/file.copy
        var op = file.copyTo(function(copiedFile) { alert("file copied"); }, null, "/temp/file.copy", false);
 
moveTo

Moves this file.

Signature
PendingOperation moveTo(in FileSystemSuccessCallback successCallback, in ErrorCallback errorCallback, in DOMString filePath, in boolean overwrite);

The file will be moved atomically to the given path. This is different to copyTo and deleting the old file, because this operation does not need extra disk space on certain platforms. If this function fails and the error callback is called, it will pass an DeviceAPIError IO_ERROR to the callback.

The encoding of file paths is UTF-8.

Errors that may be returned in the ErrorCallback:

  • SecurityError PERMISSION_DENIED_ERROR when access is denied by the security policy.
  • DeviceAPIError IO_ERROR if it is attempted to move to a directory.
  • DeviceAPIError IO_ERROR if overwrite is false and target file exists.
  • DeviceAPIError IO_ERROR if any characters in the path are not supported.
  • DeviceAPIError IO_ERROR if the file cannot be moved.
Parameters
  • successCallback: called when the file has been copied.
  • errorCallback: called if an error occurred.
  • filePath: the new file name, [a-Z0-9_- /]+ are allowed
  • overwrite: true enforces overwriting an existing file.
Return value
PendingOperation enabling the requester to cancel this request.
API features
http://bondi.omtp.org/api/1.1/filesystem.write
is obtained for the destination's root location, only if that is different from the source file's root location, or if this File object does not have full "rw" access rights.
Code example
        // moves this file to /temp/file.move
        var op = file.moveTo(function(movedFile) { file = movedFile; }, null, "/temp/file.move");
 
createDirectory

Creates a directory.

Signature
File createDirectory(in DOMString dirPath);

The new directory will be created relatively to the current directory this operation is performed on. It will attempt to create all necessary sub-directories as well. The use of "." or ".." in path components is not supported. If the bottom-most directory being created already exists this method will throw an IO_ERROR.

The encoding of file paths is UTF-8.

Parameters
  • dirPath: the new directory path, it should only contain characters supported by the underlying filesystem.
Return value
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.
Exceptions
  • SecurityError:

    PERMISSION_DENIED_ERROR if the File object does not have full "rw" access.

  • DeviceAPIError:

    IO_ERROR if the directory cannot be created.

    IO_ERROR if any characters in the path are not supported.

    IO_ERROR if a file with the same name exists.

    IO_ERROR if any path component does not exist.

    IO_ERROR if this is not a directory.

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

Creates a new empty file.

Signature
File createFile(in DOMString filePath);

The new empty file is created in the given path relatively to the current directory the operation is performed on. The use of "." or ".." in path components is not supported. If the bottom-most file being created already exists this method will throw an IO_ERROR. If any path component does not exist this method will throw an IO_ERROR.

The encoding of file paths is UTF-8.

Parameters
  • filePath: the new file path, it should only contain characters supported by the underlying filesystem.
Return value
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.
Exceptions
  • SecurityError:

    PERMISSION_DENIED_ERROR if the File object does not have full "rw" access.

  • DeviceAPIError:

    IO_ERROR if the file cannot be created.

    IO_ERROR if any characters in the path are not supported.

    IO_ERROR if the file already exists.

    IO_ERROR if any path component does not exist.

    IO_ERROR if this is not a directory.

Code example
        var newFile = dir.createFile("newFile");
 
resolve

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

Signature
File resolve(in DOMString filePath);

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

The encoding of file paths is UTF-8.

Parameters
  • filePath: the relative file/directory path to resolve.
Return value
file handle of the file or null if it cannot be resolved. The new File object will inherit its access rights from the File object on which this resolve method is called.
Exceptions
  • SecurityError:
  • DeviceAPIError:

    IO_ERROR if the file or directory cannot be resolved.

    IO_ERROR if any characters in the path are not supported.

    IO_ERROR if this is not a directory.

Code example
        var hellofile = dir.resolve("foo/hello.txt");
 
deleteDirectory

Deletes this directory.

Signature
PendingOperation deleteDirectory(in FileSystemSuccessCallback successCallback, in ErrorCallback errorCallback, in boolean recursive);

This function attempts to delete a directory or directory tree asynchronously and returns true on success, false otherwise. It may throw an IO_ERROR if a recursive deletion partially fails and any deleted data so far cannot be recovered. This might happen due the lack of filesystem permissions or if any directories or files are opened by other processes.

Errors that may be returned in the ErrorCallback:

  • SecurityError PERMISSION_DENIED_ERROR if the File object does not have full "rw" access.
  • DeviceAPIError IO_ERROR if this is a file.
  • DeviceAPIError IO_ERROR if the directory is not empty and this operation is not performed recursively.
  • DeviceAPIError IO_ERROR if the directory or any file or sub-directory cannot be deleted.
Parameters
  • successCallback: called when the directory has been successfully deleted
  • errorCallback: called if an error occurred.
  • recursive: true means a recursive deletion, this will destroy all data recursively, use with caution.
Return value
true on success
Code example
        var fullPath = dir.fullPath;
        if(dir.deleteDirectory(true)) {
                // subsequent accesses to dir will throw an error
                alert(fullPath + ' deleted');
        }
 
deleteFile

Deletes this file.

Signature
boolean deleteFile();

Returns true on success, false otherwise.

Return value
true on success
Exceptions
  • SecurityError:

    PERMISSION_DENIED_ERROR if the File object does not have full "rw" access.

  • DeviceAPIError:

    IO_ERROR if the file cannot be deleted due the lack of filesystem permissions or if it is locked or opened by another process.

    IO_ERROR if this is a directory.

Code example
        var fullPath = dir.fullPath;
        if(dir.deleteFile()) {
                // subsequent accesses to dir will throw an error
                alert(fullPath + ' deleted');
        }
 

3.5. FileStream

FileStream API.

        interface FileStream {

                readonly attribute boolean eof;

                attribute unsigned long position
                        setraises(DeviceAPIError);

                readonly attribute unsigned long bytesAvailable;

                void close();

                DOMString read(in unsigned long charCount)
                        raises(DeviceAPIError);

                ByteArray readBytes(in unsigned long byteCount)
                        raises(DeviceAPIError);

                DOMString readBase64(in unsigned long byteCount)
                        raises(DeviceAPIError);

                void write(in DOMString stringData)
                        raises(DeviceAPIError);

                void writeBytes(in ByteArray byteData)
                        raises(DeviceAPIError);

                void writeBase64(in DOMString base64Data)
                        raises(DeviceAPIError);
        };

A FileStream represents a handle to a File opened for read and/or write operations. Read and write operations are performed relative to a file pointer which 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 normal JavaScript error.

Attributes

readonly boolean eof

Indicates whether or not the current file pointer is at the end of the file.

true if the position is at the end of the current file stream.

Code example
        if(stream.eof) {
                // file has been read completely
        }
 
unsigned long position

Get/set stream position for reads/writes.

The stream position is 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 position in the position attribute.

  • DeviceAPIError:

    IO_ERROR if a position was given that is out of the stream range.

  • Code 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;
     
    readonly unsigned long bytesAvailable

    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.

    -1 if eof is true.

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

    Methods

    close

    Closes this FileStream.

    Signature
    void close();
    

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

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

    Reads the specified number of characters.

    Signature
    DOMString read(in unsigned long charCount);
    

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

    Parameters
    • charCount: number of characters being read.
    Return value
    the result of read characters as a string.
    Exceptions
    • DeviceAPIError:

      IO_ERROR if an error occurs during read.

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

    Reads the specified number of bytes from this FileStream.

    Signature
    ByteArray readBytes(in unsigned long byteCount);
    

    If 0 is supplied it will read all available bytes in a single read operation.

    Parameters
    • byteCount: number of bytes being read.
    Return value
    the result of read bytes as a byte (or number) array.
    Exceptions
    • DeviceAPIError:

      IO_ERROR if an error occurs during readBytes.

    Code 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
            }
     
    readBase64

    Reads the specified number of bytes from this FileStream, encoding the result in base64.

    Signature
    DOMString readBase64(in unsigned long byteCount);
    

    If 0 is supplied it will read all available bytes in a single read operation.

    Parameters
    • byteCount: number of bytes being read.
    Return value
    the result of read bytes as base64 encoding string.
    Exceptions
    • DeviceAPIError:

      IO_ERROR if an error occurs during readBase64.

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

    Writes the specified DOMString to this FileStream.

    Signature
    void write(in DOMString stringData);
    
    Parameters
    • stringData: the actual string to be written.
    Exceptions
    • DeviceAPIError:

      IO_ERROR if an error occurs during write.

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

    Writes the specified bytes to this FileStream.

    Signature
    void writeBytes(in ByteArray byteData);
    
    Parameters
    • byteData: the byte data array being written.
    Exceptions
    • DeviceAPIError:

      IO_ERROR if an error occurs during writeBytes.

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

    Converts the specified base64 DOMString to bytes and writes the result to this FileStream.

    Signature
    void writeBase64(in DOMString base64Data);
    
    Parameters
    • base64Data: the base64 data being written.
    Exceptions
    • DeviceAPIError:

      IO_ERROR if an error occurs during writeBase64.

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

    3.6. FileSystemManagerObject

    Specifies what is instantiated at feature request

            interface FileSystemManagerObject {
                    readonly attribute FileSystemManager filesystem;
            };
            Bondi implements FileSystemManagerObject;