繁体   English   中英

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

[英]How to recursively read local files and directories in web browser using 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,
          })
        }

两个步骤,定义一个函数,该函数应该采用一个目录并递归返回所有文件和文件夹,如下所示

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM