gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 09:04:53 25 4
gpt4 key购买 nike

使用 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 .

关于javascript - 使用 showDirectoryPicker() 访问子目录文件内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67979844/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com