how to create, read and write file in ionic native

gaurang picture gaurang · Nov 9, 2017 · Viewed 9.1k times · Source

I am looking for file operation like create, read and write text or logs in to file, i have a lot research but i haven't find any proper example to do so. this link gives the examples but when i use that in typescript file i got errors like [ts] Property 'requestFileSystem' does not exist on type 'Window'.

examples like

window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function (fs) {

    console.log('file system open: ' + fs.name);
    fs.root.getFile("newPersistentFile.txt", { create: true, exclusive: false }, function (fileEntry) {

        console.log("fileEntry is file?" + fileEntry.isFile.toString());
        // fileEntry.name == 'someFile.txt' 
        // fileEntry.fullPath == '/someFile.txt' 
        writeFile(fileEntry, null);

    }, onErrorCreateFile);

}, onErrorLoadFs);



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

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

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

        // If data object is not passed in, 
        // create a new Blob instead. 
        if (!dataObj) {
            dataObj = new Blob(['some file data'], { type: 'text/plain' });
        }

        fileWriter.write(dataObj);
    });
}

is there something which is missing? or i was doing it in a wrong-way? please help me to resolve this.

Answer

Sampath picture Sampath · Nov 9, 2017

You can easily use Ionic native File plugin.

ionic cordova plugin add cordova-plugin-file 
npm install --save @ionic-native/file