How to create a directory and file in that directory using phonegap file api?

mmathan picture mmathan · Jun 18, 2012 · Viewed 32.6k times · Source

I am using phonegap file api to create a directory and create a file in the directory created. The directory is getting created, but the file is not getting created in the directory.

The code I am using is:

document.addEventListener("deviceready", onDeviceReady, false);

function onDeviceReady() {
    window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);
}

function gotFS(fileSystem) {
    var dataDir = fileSystem.root.getDirectory("data", {create: true});
    var file = dataDir.getFile("lockfile.txt", {create: true, exclusive: true});
}

The directory data is created but lockfile.txt is not getting created.

Answer

Simon MacDonald picture Simon MacDonald · Jun 18, 2012

You need to call the code in an async manner:

document.addEventListener("deviceready", onDeviceReady, false);

function onDeviceReady() {
    window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);
}

function gotFS(fileSystem) {
   fileSystem.root.getDirectory("data", {create: true}, gotDir);
}

function gotDir(dirEntry) {
    dirEntry.getFile("lockfile.txt", {create: true, exclusive: true}, gotFile);
}

function gotFile(fileEntry) {
    // Do something with fileEntry here
}