最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin1浏览0评论

I need to read all the files and directories of a folder opened with the new File System Access API for the web. I am able to read a directory but don't know how to continue recursively on an elegant way

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

I need to read all the files and directories of a folder opened with the new File System Access API for the web. I am able to read a directory but don't know how to continue recursively on an elegant way

      try {
        const directoryHandle = await window.showDirectoryPicker()
        const files = []
        for await (let [name, handle] of directoryHandle) {
          const kind = handle.kind
          files.push({
            name,
            handle,
            kind,
          })
        }
Share Improve this question edited Feb 2 at 19:58 VLAZ 29.1k9 gold badges63 silver badges84 bronze badges asked Oct 9, 2020 at 16:14 ctwhomectwhome 8341 gold badge15 silver badges28 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 12

two steps, define one function that should take a directory and return all files and folders recursively as below

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

then invoke this function from your code as below

async function onClickHandler(e) {
    try {
        const directoryHandle = await window.showDirectoryPicker()
        const files = await listAllFilesAndDirs(directoryHandle);
        console.log('files', files);
    }catch(e) {
        console.log(e);
    }
}

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论