获取cordova目录中的文件列表

时间:2015-09-04 08:55:58

标签: javascript file cordova directory localsystem



function onDeviceReady() {
    window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, onFileSystemSuccess, onFileSystemFail);
}

function onFileSystemSuccess(fileSystem) {
    var directoryEntry = fileSystem.root;
    directoryEntry.getDirectory("MyDirectory", {create: true, exclusive: false}, onDirectorySuccess, onDirectoryFail);
}

function onDirectorySuccess(parent) {
    var directoryReader = parent.createReader();
    directoryReader.readEntries(success, fail);
}

function fail(error) {
    alert("Failed to list directory contents: " + error.code);
}

function success(entries) {
    if (entries.length == 0)
        console.log("No Records");
    else
    {
        for (var i = 0; i < entries.length; i++) {
            entries[i].file(function (file) {
                console.log("file.name " + file.name);
            })
        }
    }
    console.log('file list created');
}

function onDirectoryFail(error) {
    alert("Unable to create new directory: " + error.code);
}

function onFileSystemFail(evt) {
    console.log(evt.target.error.code);
}
&#13;
&#13;
&#13;

使用上面的代码,我得到了文件列表。但问题在于此代码是&#34; console.log(&#39;文件列表已创建&#39;)&#34;首先执行,然后执行&#34; console.log(&#39; file.name&#39; + file.name)&#34;执行。我需要列出文件名,然后列出列表创建的信息,或者我需要知道列表何时完全创建。提前谢谢。

1 个答案:

答案 0 :(得分:1)

只需将console.log放在if语句中:

function success(entries) {
    if (entries.length == 0)
        console.log("No Records");
    else
    {
        for (var i = 0; i < entries.length; i++) {
            entries[i].file(function (file) {
                console.log("file.name " + file.name);
            })
        }
        console.log('file list created');
    }
}