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

使用 File System Access 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 */ 
    }
  }
});
<button>Choose Directory</button>

最佳答案

您需要调用 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 );
    }
  }
}

Live demo , edit code .

https://stackoverflow.com/questions/67979844/

相关文章:

algorithm - 斐波那契 : non-recursive vs memoized recur

javascript - 如何在 Vue 3 模板中使用导入函数?

javascript - 如何使用 React-hook-form 和 yup 验证 React-q

python - 在python中获取每个月的最后一个星期五

SQL - Like and greater than 函数

javascript - 如何使用 Manifest v3 获取当前选项卡 URL?

.net-core - 指定的 deps.json[] 不存在 - Blazor WebAssemb

python - 如何使 spaCy 匹配不区分大小写

vue.js - vue.config.js 中的 Vue devServer.proxy 不工作

java - 刀柄不同步