【问题标题】:How to recursively read local files and directories in web browser using File System Access API如何使用文件系统访问 API 在 Web 浏览器中递归读取本地文件和目录
【发布时间】:2021-01-24 18:02:14
【问题描述】:

我需要读取使用新的 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,
          })
        }

【问题讨论】:

    标签: javascript web browser file-system-access-api


    【解决方案1】:

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

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

    【讨论】:

    猜你喜欢
    • 2021-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多