我需要读取使用新的Web文件系统访问API打开的文件夹的所有文件和目录。我能够读取目录,但不知道如何以一种优雅的方式递归继续
try {
const directoryHandle = await window.showDirectoryPicker()
const files = []
for await (let [name, handle] of directoryHandle) {
const kind = handle.kind
files.push({
name,
handle,
kind,
})
}
分两个步骤,定义一个应包含目录并递归返回所有文件和文件夹的函数,如下所示
async function listAllFilesAndDirs(dirHandle) {
const files = [];
for await (let [name, handle] of dirHandle) {
const {kind} = handle;
if (handle.kind === 'directory') {
files.push({name, handle, kind});
files.push(...await listAllFilesAndDirs(handle));
} else {
files.push({name, handle, kind});
}
}
return files;
}
然后从您的代码中调用此函数,如下所示
async function onClickHandler(e) {
try {
const directoryHandle = await window.showDirectoryPicker()
const files = await listAllFilesAndDirs(directoryHandle);
console.log('files', files);
}catch(e) {
console.log(e);
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句