Scott Casey
Scott Casey

Reputation: 85

How to iterate over the contents of a FileSystemDirectoryHandle?

I'm working on a chrome extension to streamline some of my work. This extension needs access to files on my computer in order to upload them and work with them. I'm trying to iterate over the contents of a directory using the File System Access API. According to the documentation on FileSystemDirectoryHandle, I should be able to use the values() method of the directory handle to iterate over the contents of the directory. However, when I do this in my test code, I get an error that directoryHandle.values is not a function or its return value is not iterable.

Here's the code I'm testing at the moment (updateDirectory is called when a button is clicked):

async function updateDirectory(){
  const directoryHandle = await getDirectory();
  console.log('directoryHandle',directoryHandle);
  for(let handle of directoryHandle.values()){
    console.log('handle',handle);
  }
}

const getDirectory = ()=>{
  if(!window.showDirectoryPicker){
    alert('Unsupported Browser Notice');
    return;
  }
  const verify = confirm('Ask user to confirm');
  if(!verify) return 'File picker canceled.';
  return window.showDirectoryPicker();
};

The output from the first log statements is:

directoryHandle
FileSystemDirectoryHandle{
  kind:"directory"
  name:"correct name of directory"
  [[Prototype]]:FileSystemDirectoryHandle
}

So, I know that the directory handle is being returned correctly. The second log statement isn't displayed of course because the for loop errors out with the error described above.

So, what piece of the File System Access API am I misunderstanding here?

Upvotes: 2

Views: 2135

Answers (1)

Scott Casey
Scott Casey

Reputation: 85

And, the issue was that I wasn't awaiting the return value of .values(). E.g.

async function updateDirectory(){
  const directoryHandle = await getDirectory();
  console.log('directoryHandle',directoryHandle);
  for await(let handle of directoryHandle.values()){
    console.log('handle',handle);
  }
}

Upvotes: 3

Related Questions