Training Guide: Programming in HTML5 with JavaScript and CSS3 Ebook

(Nora) #1

604 CHAPTER 16 Offline web applications


fileReader.onerror = function() { alert('Failed'); };
fileReader.readAsText(file);
}

function handleError(error) {
alert(error.code);
}

In addition to the readAsText method, the FileReader object contains the readArrayBuffer
and readAsDataURL methods for reading content types other than text.

Deleting a file


The last file operation covered in this section is deleting a file. Like the other operations, this
requires a FileEntry object. Because the FileEntry object inherits from the Entry object, it has
a remove method to remove itself from the file system. It accepts both a successCallback call
and an onError callback, as demonstrated in the following example.
window.requestFileSystem(TEMPORARY, 5 * 1024 * 1024, getFile, handleError);

function getFile(fileSystem) {
fileSystem.root.getFile("example.txt", { create: true }, fileOpened, handleError);
}

function fileOpened(fileEntry) {
fileEntry.remove(fileRemoved, handleError);
}

function fileRemoved() {
alert('Success');
}

function handleError(error) {
alert(error.code);
}

Creating and opening a directory


Working with directories within the FileSystem API is very similar to working with files. For
example, to open or create a file, use the getFile method. To do the same with a directory, use
the getDirectory method.
The following example creates a new directory called “Chapter16”. If it’s created success-
fully, its full path is displayed.
window.requestFileSystem(TEMPORARY, 5 * 1024 * 1024, getDirectory, handleError);

function getDirectory(fileSystem) {
fileSystem.root.getDirectory("Chapter16", { create: true },
directoryOpened, handleError);
}
Free download pdf