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

问题描述 投票:0回答:3

我尝试使用 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)。

javascript cordova cordova-plugins
3个回答
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.
}

0
投票

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

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


0
投票

https://tunnel.imo.im/s/object/.G5nBZOJAjqbbqOhATYEBpZDXpTR/voice.aac"], ["", "2024-07-31 14:36:58", "我", "上传的音频:

© www.soinside.com 2019 - 2024. All rights reserved.