如何获取所有文件和文件夹结构的JSON对象

时间:2016-07-26 10:36:31

标签: javascript cordova cordova-plugins

我尝试使用Cordova构建一个函数,它为我提供了一个如下所示的JSON对象:

{
  "file:///storage/emulated/0/Android/data/test/files/data/bla.txt": "bla.txt",
  "file:///storage/emulated/0/Android/data/test/files/data/HelloWorld.txt": "HelloWorld.txt",
  "file:///storage/emulated/0/Android/data/test/files/data/RSC/picture-1469199158993.jpg": "picture-1469199158993.jpg",
  "file:///storage/emulated/0/Android/data/test/files/data/RSC/picture-1469199665434.jpg": "picture-1469199665434.jpg",
  "file:///storage/emulated/0/Android/data/test/files/data/API-Test/test/datFile.txt": "datFile.txt",
  "file:///storage/emulated/0/Android/data/test/files/data/RSC/thumbnails/picture-1469199158993.jpg": "picture-1469199158993.jpg",
  "file:///storage/emulated/0/Android/data/test/files/data/RSC/thumbnails/picture-1469199665434.jpg": "picture-1469199665434.jpg"
}

我的问题是Cordova函数是异步的,所以我的函数返回一个空对象。

到目前为止,这是我的解决方案:

var dirObj = new Object();

function getFiles(fullPath, callback){
    dirObj = new Object();

    window.resolveLocalFileSystemURL(fullPath, addFileEntry, function(e){
            console.error(e);
    });

    return JSON.stringify(dirObj);    
}

var addFileEntry = function (entry) {
  var dirReader = entry.createReader();
  dirReader.readEntries(
    function (entries) {
      var fileStr = "";
      for (var i = 0; i < entries.length; i++) {
        if (entries[i].isDirectory === true) {
          addFileEntry(entries[i]);
        } else {
          dirObj[entries[i].nativeURL] = entries[i].name;
          console.log(entries[i].fullPath);
        }
      }
    },
    function (error) {
      console.error("readEntries error: " + error.code);
    }
  );
};

注意:Promise()不是一个选项,因为该函数必须在Chrome 30.0上运行,而Promise()从32.0开始可用(src)。

2 个答案:

答案 0 :(得分:0)

我找到了类似于@AxelH建议解决方案的解决方案。 我用了一个数组: 每次我调用函数addFileEntry时,我都会将id压入数组。函数完成后,我从数组中删除了id。如果数组为空,我调用了回调函数。

感谢@AxelH的帮助,感谢@gcampbell提到我不知道的蓝鸟,并将用于javascript中的其他异步问题。

答案 1 :(得分:0)

var dirObj;

function getFiles(fullPath, callback){
    dirObj = new Object();

    window.resolveLocalFileSystemURL(fullPath, addFileEntry, function(e){
            console.error(e);
    });
}

var counter = 0;

var addFileEntry = function (entry) {
  ++counter;
  var dirReader = entry.createReader();
  [...] //you probably should do it in the readEntries function to since this is async to (as you said), because this could still run while the following line might be executed. If so, just add the same if(...) callback();
  if(--counter == 0)
      callBack();
};

function callBack(){
   var json = JSON.stringify(dirObj);
   //Do what you need with it.
}