Cordova writing to a folder within the app structure

Viewed 128

Using the Cordova file plugin how can I write files to a folder within the app? I realise I can't use the www folder but how can I create a folder within the app to write to? Ideally where it cannot be opened by a third party when compiled.

The code I am using is as follows:

function createFile() {
 var type = window.TEMPORARY;
 var size = 5*1024*1024;
 window.requestFileSystem(type, size, successCallback, errorCallback)

 function successCallback(fs) {
  fs.root.getFile('log.txt', {create: true, exclusive: true}, function(fileEntry) {
     alert('File creation successfull!')
  }, errorCallback);
 }

 function errorCallback(error) {
  alert("ERROR: " + error.code)
 }

}

Thanks in advance;

1 Answers

Personally I'd use the cordova.file constants

Creating a directory

window.resolveLocalFileSystemURL(cordova.file.dataDirectory, function(directoryEntry) {
    directoryEntry.getDirectory("logDirectory", { create: true }, function(logDirectoryEntry) {
        logDirectoryEntry.getFile("log.txt", {create: true}, function (logFileEntry) {
            // Write file (see example below)
        });
    });
}, onError);

Writing a file

window.resolveLocalFileSystemURL(cordova.file.dataDirectory + "/log.txt", function(fileEntry) {
    fileEntry.createWriter(function(writer) {
        writer.onwriteend = function() {
            console.log("Success!");
        };

        writer.onerror = function(e) {
            console.log("Error :(", e);
        };

        writer.write("Hello");
    });
}, onError);

Refer to the File System Layouts for the available cordova.file constants and where they are located physically on the file system, as well as additional details for both iOS and android platforms.

cordova.file.dataDirectory is stored in the application's data container where no app, other than the app process itself has access to. The data will remain there unless the app deletes it or the app is uninstalled, or the user uses an OS function to clear the app (Android has a Clear Data button for example under App Info).

If you don't want files to be visible by third-party then stay away from any of the external file paths, such as cordova.file.externalDataDirectory

Related