Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing sub-directory file content using showDirectoryPicker()

Using the File System Access API, how would I access the files contained within a folder of the chosen directory?

document.querySelector('button').addEventListener('click', async () => {
  const dirHandle = await window.showDirectoryPicker();
  for await (const entry of dirHandle.values()) {
    if (entry.kind === "file"){
      const file = await entry.getFile();
      const text = await file.text();
      console.log(text);
    }
    if (entry.kind === "directory"){
      /* for file in this directory do something */ 
    }
  }
});
<button>Choose Directory</button>
like image 210
Conrad Klek Avatar asked Aug 15 '26 21:08

Conrad Klek


1 Answers

A small improvement to Kaiido's answer:

btn.onclick = async (evt) => {
  const out = {};
  const dirHandle = await showDirectoryPicker();  
  await handleDirectoryEntry( dirHandle, out );
  console.log( out );
};
async function handleDirectoryEntry( dirHandle, out ) {
  for await (const entry of dirHandle.values()) {
    if (entry.kind === "file"){
      const file = await entry.getFile();
      out[ file.name ] = file;
    }
    if (entry.kind === "directory") {
      const newOut = out[ entry.name ] = {};
      await handleDirectoryEntry( entry, newOut );
    }
  }
}

dirHandle.values() returns a list of objects that inherit from FileSystemHandle, there are two possibilities: either FileSystemFileHandle or FileSystemDirectoryHandle.

Since const entry already is a FileSystemDirectoryHandle in case when entry.kind is "directory" there is no need to call dirHandle.getDirectoryHandle()

like image 117
Jinjinov Avatar answered Aug 18 '26 11:08

Jinjinov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!