3

我正在使用 Javascript 编写一个应用程序,该应用程序将与 Phonegap 一起使用来制作一个 Android 应用程序。我正在使用 Phonegap File API 来读取目录和文件。相关代码如下所示:

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

// PhoneGap is ready
//
function onDeviceReady() {
    window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, onFileSystemSuccess, fail);
}

function onFileSystemSuccess(fileSystem) {
    fileSystem.root.getDirectory("/sdcard", {create: false, exclusive: false}, getDirSuccess, fail);
}

function getDirSuccess(dirEntry) {
    // Get a directory reader
    var directoryReader = dirEntry.createReader();

    // Get a list of all the entries in the directory
    directoryReader.readEntries(readerSuccess,fail);
}

var numDirs = 0;
var numFiles = 0;

function readerSuccess(entries) {
    var i;
    for (i=0; i<entries.length; i++) 
    {
        if(entries[i].isFile === true)
        {
        numFiles++;
        entries[i].file(fileSuccess,fail);
        }
        else if (entries[i].isDirectory === true)
        {
        numDirs++;
        getDirSuccess(entries[i]);
        }
    }
}

所以到目前为止,该程序运行良好。阅读器将读取 /sdcard 目录的内容。如果它遇到一个文件,它将调用 fileSuccess(为简洁起见,我在代码中将其排除),如果它遇到另一个目录,它将再次调用 getDirSuccess。我的问题是:我怎么知道整个 /sdcard 目录何时被读取?如果不多次通过 /sdcard 目录,我想不出一种好方法来完成此任务。任何想法表示赞赏,并提前感谢您!

4

2 回答 2

2

+1 提出了一个好问题,因为无论如何我自己都必须这样做。我会使用旧的 setTimeout 技巧。一旦取消不再发生,您就知​​道您已经完成并且可以触发您的事件,但只需确保它只触发一次。

这就是我的意思,我将变量命名为 long 只是为了更具可读性(不是我的风格)......

// create timeout var outside your "readerSuccess" function scope
var readerTimeout = null, millisecondsBetweenReadSuccess = 100;

function readerSuccess(entries) {
    var i = 0, len = entries.length;
    for (; i < len; i++) {
        if (entries[i].isFile) {
            numFiles++;
            entries[i].file(fileSuccess,fail);
        } else if (entries[i].isDirectory) {
            numDirs++;
            getDirSuccess(entries[i]);
        }
        if (readerTimeout) {
            window.clearTimeout(readerTimeout);
        }
    }
    if (readerTimeout) {
        window.clearTimeout(readerTimeout);
    }
    readerTimeout = window.setTimeout(weAreDone, millisecondsBetweenReadSuccess);
}

// additional event to call when totally done
function weAreDone() {
   // do something
}

因此,其中的逻辑是您在阅读内容时不断取消调用“weAreDone”函数。不确定这是否是最好的方法或更有效的方法,但在适当的“毫秒间读取成功”的情况下,它不会导致一个以上的循环。

于 2012-06-27T21:37:42.623 回答
1

与其使用 setTimeout(如果您的设备非常慢,这可能会失败),您可以使用计数器来查看仍然需要调用多少回调。如果计数器达到零,你就完成了:)

这是递归代码:

var fileSync = new function(){
    this.filesystem = null;

    this.getFileSystem = function(callback){
        var rfs = window.requestFileSystem || window.webkitRequestFileSystem;

        rfs(
              1// '1' means PERSISTENT
            , 0// '0' is about max. storage size: 0==we don't know yet
            , function(filesystem){
                fileSync.filesystem = filesystem;
                callback(filesystem);
            }
            , function(e){
                alert('An error occured while requesting the fileSystem:\n\n'+ e.message);
            }
        );
    }

    this.readFilesFromReader = function(reader, callback, recurse, recurseFinishedCallback, recurseCounter)
    {
        if (recurse && !recurseCounter)
            recurseCounter = [1];

        reader.readEntries(function(res){
                callback(res);

                if (recurse)
                {
                    for (var i=0; i<res.length; i++) {
                        /* only handle directories */
                        if (res[i].isDirectory == true)
                        {
                            recurseCounter[0]++;
                            fileSync.readFilesFromReader(res[i].createReader(), callback, recurse, recurseFinishedCallback, recurseCounter);
                        }
                    }
                }
                /* W3C specs say: Continue calling readEntries() until an empty array is returned.
                 * You have to do this because the API might not return all entries in a single call.
                 * But... Phonegap doesn't seem to accommodate this, and instead always returns the same dir-entries... OMG, an infinite loop is created :-/
                */
                //if (res.length)
                //  fileSync.readFilesFromReader(reader, callback, recurse, recurseFinishedCallback, recurseCounter);
                //else
                if (recurse && --recurseCounter[0] == 0)
                {
                    recurseFinishedCallback();
                }
            }
        , function(e){
            fileSync.onError(e);
            if (recurse && --recurseCounter[0] == 0)
                recurseFinishedCallback();
        });
    };

    this.onError = function(e){
        utils.log('onError in fileSync: ' + JSON.stringify(e));
        if (utils.isDebugEnvironment())
            alert('onError in fileSync: '+JSON.stringify(e));
    }
}

var utils = new function(){
    this.log = function(){
        for (var i=0;i<arguments.length;i++)
            console.log(arguments[i]);
    }
    this.isDebugEnvironment = function(){ return true }// simplified
}

测试这个的示例代码:

var myFiles = [];
var directoryCount = 0;

window.onerror = function(){ alert('window.onerror=\n\n' + arguments.join('\n')) }

var gotFilesCallback = function(entries)
{
    for (var i=0;i<entries.length;i++)
    {
        if (entries[i].isFile == true)
            myFiles.push(entries[i].fullPath)
        else
            ++directoryCount;
    }
}

var allDoneCallback = function(){
    alert('All files and directories were read.\nWe found '+myFiles.length+' files and '+directoryCount+' directories, shown on-screen now...');
    var div = document.createElement('div');
    div.innerHTML = '<div style="border: 1px solid red; position: absolute;top:10px;left:10%;width:80%; background: #eee;">'
        + '<b>Filesystem root:</b><i>' + fileSync.filesystem.root.fullPath + '</i><br><br>'
        + myFiles.join('<br>').split(fileSync.filesystem.root.fullPath).join('')
    + '</div>';
    document.body.appendChild(div);
}

/* on-device-ready / on-load, get the filesystem, and start reading files */
var docReadyEvent = window.cordova ? 'deviceready':'load';
document.addEventListener(docReadyEvent, function()
{
    fileSync.getFileSystem(function(filesystem){
        var rootDirReader = filesystem.root.createReader();
        fileSync.readFilesFromReader(rootDirReader, gotFilesCallback, true, allDoneCallback);
    })
}, false);
于 2014-01-23T13:41:59.137 回答