javascriptwebbrowserfile-system-access-api

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


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

Solution

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