使用 showDirectoryPicker() 访问子目录文件内容

Con*_*lek 2 html javascript file-system-access-api

使用文件系统访问 API,我将如何访问所选目录的文件夹中包含的文件?

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 */ 
    }
  }
});
Run Code Online (Sandbox Code Playgroud)
<button>Choose Directory</button>
Run Code Online (Sandbox Code Playgroud)

Jin*_*nov 7

对 Kaiido 的答案的一个小改进:

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 );
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

dirHandle.values()返回继承自 的对象列表FileSystemHandle,有两种可能性:FileSystemFileHandleFileSystemDirectoryHandle

既然const entry已经是万一FileSystemDirectoryHandle什么时候entry.kind"directory"不需要打电话了 dirHandle.getDirectoryHandle()


Kai*_*ido 5

您需要调用该dirHandle.getDirectoryHandle(name, options)方法,并将name参数设置为您条目的.name.

下面是一个示例代码,它将遍历传递的目录并构建它找到的文件的树。

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 newHandle = await dirHandle.getDirectoryHandle( entry.name, { create: false } );
      const newOut = out[ entry.name ] = {};
      await handleDirectoryEntry( newHandle, newOut );
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

现场演示编辑代码