如何使用javascript迭代文件系统目录和文件?

时间:2012-06-27 21:17:26

标签: javascript android cordova sd-card fileapi

我正在使用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目录多次,我想不出一个很好的方法来完成这个。任何想法都表示赞赏,并提前感谢您!

2 个答案:

答案 0 :(得分:2)

+1一个好问题,因为我自己必须这样做。我会使用旧的setTimeout技巧。一旦取消不再发生,你知道你已经完成并可以解雇你的事件,但只是确保它只被解雇一次。

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

// 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”函数。不确定这是最好的方法还是更有效但是在给定适当的“millisecondsBetweenReadSuccess”的情况下不会导致多个循环。

答案 1 :(得分: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);