pandafy
pandafy

Reputation: 193

How to read object written through cordova file plugin?

I read on Cordova's documentation for android platform a code snipped and tried to use it for writing a JS object on a text file. The object gets successfully written but when I read it with FileReader API I can't get output as expected.

function writeFile(fileEntry, dataObj, isAppend) {
    // Create a FileWriter object for our FileEntry (log.txt).
    fileEntry.createWriter(function (fileWriter) {

        fileWriter.onwriteend = function() {
            console.log("Successful file read...");
            readFile(fileEntry);
        };

        fileWriter.onerror = function (e) {
            console.log("Failed file read: " + e.toString());
        };

        // If we are appending data to file, go to the end of the file.
        if (isAppend) {
            try {
                fileWriter.seek(fileWriter.length);
            }
            catch (e) {
                console.log("file doesn't exist!");
            }
        }
        fileWriter.write(dataObj);
    });
}

function readFile(fileEntry) {

    fileEntry.file(function (file) {
        var reader = new FileReader();

        reader.onloadend = function() {
            console.log("Successful file read: " + this.result);

            //displayFileData(fileEntry.fullPath + ": " + this.result);
        };
        reader.onload = function(){
            k=reader.readAsText(file);

        };
       reader.readAsText(file);

    },onErrorLoadFs );
}

Format of object I want to read :

function sub(name,absent,present){
    this.name=name;
    this.absent=absent;
    this.present=present;

}

var S = new sub('Physics',1,3);
var k= new sub();

What exactly I want to do :

I am writing an object S on the file which appears like this when opened

{"name":"Physics","absent":1, "present" : 3}

Now after reading the file (which in my case is filetoAppend.txt) I want to assign these values to another object k so that when I run k.name, Physics is shown as output.

console output

k
"{"name":"Physics","absent":1,"present":3}"
k.name
undefined

Upvotes: 3

Views: 1782

Answers (1)

NullPointer
NullPointer

Reputation: 7368

With the Cordova File Plugin, there are two essential pieces of information to remember:

1.Like all Cordova plugins, you have to wait for the deviceready event before you try anything,

2.Then, Use window.resolveLocalFileSystemURL(<path>, <successHandler>, <errorHandler>)

window.resolveLocalFileSystemURL() returns a FileEntry or DirectoryEntry instance (depending on whether you gave a file or a directory as path as its first parameter), which you can then work with.

WRITING TO A FILE

document.addEventListener('deviceready', onDeviceReady, false);  
function onDeviceReady() {  
    function writeToFile(fileName, data) {
        data = JSON.stringify(data, null, '\t');
        window.resolveLocalFileSystemURL(cordova.file.dataDirectory, function (directoryEntry) {
            directoryEntry.getFile(fileName, { create: true }, function (fileEntry) {
                fileEntry.createWriter(function (fileWriter) {
                    fileWriter.onwriteend = function (e) {
                        // for real-world usage, you might consider passing a success callback
                        console.log('Write of file "' + fileName + '"" completed.');
                    };

                    fileWriter.onerror = function (e) {
                        // you could hook this up with our global error handler, or pass in an error callback
                        console.log('Write failed: ' + e.toString());
                    };

                    var blob = new Blob([data], { type: 'text/plain' });
                    fileWriter.write(blob);
                }, errorHandler.bind(null, fileName));
            }, errorHandler.bind(null, fileName));
        }, errorHandler.bind(null, fileName));
    }

    writeToFile('example.json', { foo: 'bar' });
}

WRITING FROM FILE

document.addEventListener('deviceready', onDeviceReady, false);  
function onDeviceReady() {  
    function readFromFile(fileName, cb) {
        var pathToFile = cordova.file.dataDirectory + fileName;
        window.resolveLocalFileSystemURL(pathToFile, function (fileEntry) {
            fileEntry.file(function (file) {
                var reader = new FileReader();

                reader.onloadend = function (e) {
                    cb(JSON.parse(this.result));
                };

                reader.readAsText(file);
            }, errorHandler.bind(null, fileName));
        }, errorHandler.bind(null, fileName));
    }

    var fileData;
    readFromFile('data.json', function (data) {
        fileData = data;
    });
}

cb is the callback function that you need to pass when calling this function

For full reference use:https://www.neontribe.co.uk/cordova-file-plugin-examples/

Updated based on your updated Question

In reader.onloadend you can get the result of the file and assign to your output object k or can call callback function incase.

reader.onloadend = function (e) {
   //cb(JSON.parse(this.result));
   var k=JSON.parse(this.result);
   console.log(k.name + ", " + k.absent+ ", " + k.present);
  };

var k = JSON.parse('{"name":"Physics","absent":1, "present" : 3}');
console.log(k.name + ", " + k.absent + ", " + k.present);

Upvotes: 2

Related Questions