4

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

1 Answer 1

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);
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.