我正在开发一个 chrome 扩展来简化我的一些工作。此扩展需要访问我的计算机上的文件才能上传它们并使用它们。我正在尝试使用 File System Access API 迭代目录的内容。根据 FileSystemDirectoryHandle 上的文档,我应该能够使用目录句柄的 values()
方法来迭代目录的内容。但是,当我在测试代码中执行此操作时,出现错误:directoryHandle.values 不是函数或其返回值不可迭代
。
这是我目前正在测试的代码(单击按钮时调用 updateDirectory
):
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();
};
第一个日志语句的输出是:
directoryHandle
FileSystemDirectoryHandle{
kind:"directory"
name:"correct name of directory"
[[Prototype]]:FileSystemDirectoryHandle
}
所以,我知道目录句柄已正确返回。当然,第二条日志语句不会显示,因为 for 循环出错并出现上述错误。
那么,我在这里误解了文件系统访问 API 的哪一部分?
最佳答案
而且,问题是我没有等待 .values()
的返回值。例如
async function updateDirectory(){
const directoryHandle = await getDirectory();
console.log('directoryHandle',directoryHandle);
for await(let handle of directoryHandle.values()){
console.log('handle',handle);
}
}
关于javascript - 如何迭代 FileSystemDirectoryHandle 的内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72205424/