4

The use case here is not that important though but the use actually is. I want to browse the users local file system via browser like we do via <input type="file"> but instead of picking up a file I want to pick up a directory and get list of all the files and directories inside it.

Once I get that list of files I want to recursively show them in a treeview like structure.

This is a example of what I know can be done via File System Access Api.

I just want to use this API to create something like a File Manager or a treeview.

Thanks.

2
  • Bye bye privacy, if you want to open the entire disk drive like a file manager. Commented Jun 20, 2022 at 13:41
  • 1
    @JoopEggen It's not a attack on privacy. As the user will be picking the directory they want to give access by themselves. Commented Jun 28, 2022 at 5:58

1 Answer 1

4

To enumerate all files in a directory, call showDirectoryPicker(). The user selects a directory in a picker, after which a FileSystemDirectoryHandle is returned, which lets you enumerate and access the directory's files.

const button = document.getElementById('button');
button.addEventListener('click', async () => {
  const dirHandle = await window.showDirectoryPicker();
  for await (const entry of dirHandle.values()) {
    console.log(entry.kind, entry.name);
  }
});

If you additionally need to access each file via getFile() to, for example, obtain the individual file sizes, do not use await on each result sequentially, but rather process all files in parallel, for example, via Promise.all().

const button = document.getElementById('button');
button.addEventListener('click', async () => {
  const dirHandle = await window.showDirectoryPicker();
  const promises = [];
  for await (const entry of dirHandle.values()) {
    if (entry.kind !== 'file') {
      break;
    }
    promises.push(entry.getFile().then((file) => `${file.name} (${file.size})`));
  }
  console.log(await Promise.all(promises));
});
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks, but why "not use await on each result sequentially"?
Processing sequentially would be slower. Processing everything in parallel is the faster alternative.
does your for await isn't sequentially wait for each of dirHandle.values?
The FileSystemDirectoryHandle.values() method returns an asynchronous iterator, see the documentation. Getting a file via getFile() is the asynchronous operation that is being parallelized.

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.