Search code examples
javascripthtmlcordovaclosureshtml5-filesystem

Simple readFile() function in HTML5 / Cordova


Here is a simple function that should return the contents of given file in current directory. It reads the file contents correctly, but when I want to return it, it fails to do so. reader.onloadend is called when data are read. How can I make it return data from that function?

readFile: function(fileName) {
        app.fs.data = "{}"; // clear whatever was stored before
        var hasFile = function(fileEntry) {
            var gotFile = function(file) {
                var reader = new FileReader();
                reader.onloadend = function(evt) {
                    app.fs.data = evt.target.result;
                    console.log("Read as Text: " + file.name);
                    console.log("Data: " + app.fs.data); // app.fs.data contains correct data
                };
                reader.onerror = function(e) {
                    console.log("Error: " + e);
                };
                reader.readAsText(file);
            };
            fileEntry.file(gotFile, app.fs.fail);
        };
        app.fs.dir.getFile(fileName, null, hasFile, app.fs.fail);
        console.log("Actual data: " + app.fs.data); // app.fs.data contains INCORRECT data "{}"
        return app.fs.data;
    }

Console output:

Actual data: {}:92
Read as Text: article.json:81
Data: {"id":1405518906105,"name":"My Name","category":0,"abstract":"","content":"","published":false,"lastPublish":null}:82

Solution

  • Finally understood, that my code makes no sense. I end up using JavaScript Promises, a way to handle async based functions with elegance. For more read here: http://www.html5rocks.com/en/tutorials/es6/promises/

    Since Cordova doesn't support Promises, like Chrome or other browser I used this library which has the much needed functionality: https://github.com/tildeio/rsvp.js

    There are also many other libraries which implement Promises and other async helpers, just use google.