Lesson 3: Working with the FileSystem API CHAPTER 16 605
function directoryOpened(directoryEntry) {
alert(directoryEntry.fullPath); // will display "/Chapter16"
}
function handleError(error) {
alert(error.code);
}
Writing a file to a directory
You learned to add a file to the root directory of your application’s file system. The following
example writes the file to a new subdirectory.
window.requestFileSystem(TEMPORARY, 5 * 1024 * 1024, getDirectory, handleError);
function getDirectory(fileSystem) {
fileSystem.root.getDirectory("Chapter16", { create: true },
directoryOpened, handleError);
}
function directoryOpened(directoryEntry) {
directoryEntry.getFile("example.txt", { create: true }, fileOpened, handleError);
}
function fileOpened(fileEntry) {
fileEntry.createWriter(writeToFile, handleError);
}
function writeToFile(fileWriter) {
fileWriter.onwriteend = function() { alert('Success'); };
fileWriter.onerror = function() { alert('Failed'); };
fileWriter.seek(fileWriter.length);
fileWriter.write(new Blob(['Hello world'], {type: 'text/plain'}));
}
function handleError(error) {
alert(error.code);
}
Deleting a directory
The DirectoryEntry object also inherits from the Entry object, which provides a remove
method for deleting itself from the file system. However, this method can be used for empty
directories only. An error is thrown if the directory contains other subdirectories or files.
window.requestFileSystem(TEMPORARY, 5 * 1024 * 1024, getDirectory, handleError);
function getDirectory(fileSystem) {
fileSystem.root.getDirectory("Chapter16", { create: true },
directoryOpened, handleError);
}