如何使用文件系统访问在 Web 浏览器中递归读取本地文件和目录 API

How to recursively read local files and directories in web browser using File System Access API

我需要读取使用新文件系统访问 API 为 Web 打开的文件夹的所有文件和目录。我能够读取目录,但不知道如何以优雅的方式继续递归

      try {
        const directoryHandle = await window.showDirectoryPicker()
        const files = []
        for await (let [name, handle] of directoryHandle) {
          const kind = handle.kind
          files.push({
            name,
            handle,
            kind,
          })
        }

两步,定义一个函数,该函数应该递归地获取目录和return所有文件和文件夹,如下所示

    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);
    }
}