Lesson 3: Working with the FileSystem API CHAPTER 16 603
window.requestFileSystem(TEMPORARY, 5 * 1024 * 1024, getFile, handleError);
function getFile(fileSystem) {
fileSystem.root.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.write(new Blob(['Hello world'], {type: 'text/plain'}));
}
function handleError(error) {
alert(error.code);
}
If you were opening an existing file and wanted to append new data at the end of the file,
you would use the seek method to point the cursor to the end of the file as follows.
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'}));
}
Reading a file
The FileEntry object also has a file method, which makes it return a File object. After you
have a reference to a File object, you can read it by using the FileReader object. Similar to
FileWriter, you must set your onloadend and onerror callbacks before making a read attempt.
The following example uses the readAsText method to read the contents of the file and
store it in a string that can then be accessed in the this.result value within the onloadend
callback.
window.requestFileSystem(TEMPORARY, 5 * 1024 * 1024, getFile, handleError);
function getFile(fileSystem) {
fileSystem.root.getFile("example.txt", { create: true }, fileOpened, handleError);
}
function fileOpened(fileEntry) {
fileEntry.file(readFile, handleError);
}
function readFile(file) {
var fileReader = new FileReader();
fileReader.onloadend = function() { alert(this.result); };