The FileReader API works great as long as the file you want to read is on the device's file system. However if you want to read a file you've packed in the Android assets folder you would need to use XHR to read the file. I'm providing an interface that follows the same API as the regular FileReader. Of course the
XhrFileReader is not limited to only reading files from the assets folder, it can also read files from the file system and over HTTP.
Adding the plugin to your project
To install the plugin, move XhrFileReader.js to your project's www folder and include a reference to it in your html files.
Using the plugin
To instantiate a new reader use the folling code:
var reader = cordova.require("cordova/plugin/xhrfilereader");
Setup your event handlers:
// called once the reader begins
reader.onloadstart = function() {
console.log("load start");
};
// called when the file has been completely read
reader.onloadend = function(evt) {
console.log("File read");
console.log(evt.target.result);
};
Unfortunately, you will only get an error on files read over HTTP. When you specify a file:// path the request status is always 0. There is no way to tell between a successful read or an error. So if you specify a file that does not exist like "file:///does.not.exist.txt" you will get an empty evt.target.result in your onloadend handler.
// called if the reader encounters an error
reader.onerror = function(error) {
console.log("Error: " + error.code);
};
Progress events are fired but are not very useful as they don't contain partial results.
// called while the file is being read
reader.onprogress = function(evt) {
console.log("progress");
};
Finally call your read method, for instance:
reader.readAsText("http://www.google.com");
reader.readAsText("file:///android_asset/www/config.json");
reader.readAsText("file:///sdcard/error.log");
and that's about it. Obviously, this plugin is most useful when you need to read a text file from the assets folder.