ctw*_*ome 4 javascript browser web file-system-access-api
我需要读取使用新的 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,
})
}
Run Code Online (Sandbox Code Playgroud)
RAJ*_*RAJ 12
两步,定义一个函数,该函数应该采用一个目录并递归返回所有文件和文件夹,如下所示
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;
}
Run Code Online (Sandbox Code Playgroud)
然后从您的代码中调用此函数,如下所示
async function onClickHandler(e) {
try {
const directoryHandle = await window.showDirectoryPicker()
const files = await listAllFilesAndDirs(directoryHandle);
console.log('files', files);
}catch(e) {
console.log(e);
}
}
Run Code Online (Sandbox Code Playgroud)