Search code examples
native-file-system-api-js

Get a list of all files within a directory in a client machine using browser


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.


Solution

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