<button id="btn">访问文件夹</button>
<script>
const btn = document.querySelector('#btn')
btn.onclick = async () => {
try {
const handle = await showDirectoryPicker();
const root = await processHandler(handle) || []
// console.log('root', root)
// 拿到文件内容
for(let i = 0; i < root.children.length; i++) {
// 获取文件内容
const file = await root.children[i].getFile()
console.log('file', file)
// 渲染文件内容
const fileReader = new FileReader()
// 根据文件内容对应渲染
const fileType = ['text/javascript', 'text/html']
if (fileType.includes(file.type)) {
fileReader.readAsText(file, 'utf-8')
// 读取结果
fileReader.onload = e => {
console.log('result', e.target.result)
}
}
}
} catch (error) {
console.log(error)
}
}
async function processHandler(handle) {
// 判断如果是文件,而不是文件夹
if (handle.kind === 'file') {
console.log('handle', handle)
return handle
}
handle.children = [] // 保存子文件夹的内容
const iter = await handle.entries() // 获取文件夹中所有的内容; iter异步迭代器
// iter: 异步迭代器
for await (const iterator of iter) {
// console.log('iter', iterator[1]) // 递归处理文件夹中的内容
const subHandle = await processHandler(iterator[1])
handle.children.push(subHandle)
}
return handle
}
</script>