3
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <button id="btn">选择文件夹</button>
</body>
</html>
<script>
// https://developer.mozilla.org/en-US/docs/Web/API/Window/showDirectoryPicker
const btnDom = document.getElementById("btn")
btnDom.onclick =async () =>{
    try {
        const directory =await window.showDirectoryPicker()
        const root = await processDirectory(directory)
        await renderAllFile(root)
    } catch (error) {
        console.error(error)
    }
}
const fileKind = 'file'
const processDirectory =async (directory) => {
    if(directory.kind === fileKind){
        return directory
    }
    directory.children = []
    const iter = directory.entries()
    for await (const item of iter) {
        directory.children.push(await processDirectory(item[1]))
    }
    return directory
}
const renderAllFile =async (root) => {
    const rootType =Array.isArray(root)
    const rootfiles = rootType ? root : [root]
    for (let i = 0;i < rootfiles.length; i++) {
        const rootItem = rootfiles[i]
        if(rootItem.kind === fileKind){
            await readerFile(rootItem)
        }
        if((rootItem?.children || [])?.length){
            await renderAllFile(rootItem?.children)
        }
    }
}
const readerFile =async (fileHandle) => {
    const file = await fileHandle.getFile()
    const render = new FileReader()
    render.onload = (e) => {
        const fileText = e.target.result
        console.log(file.name,fileText);
    }
    render.readAsText(file, 'utf-8')
}
</script>

白水
1.8k 声望391 粉丝