gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 05:45:10 25 4
gpt4 key购买 nike

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

最佳答案

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.
}

关于javascript - 如何获取所有文件和文件夹结构的 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38587536/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com