概述目录选择器允许用户选中目录并授权访问。本文展示递归遍历与批量读取的实现与降级策略。能力与权限const supportsDirPicker = typeof window.showDirectoryPicker === 'function'; async function requestPerm(handle, mode = 'read') { if (typeof handle.requestPermission === 'function') { const s = await handle.requestPermission({ mode }); return s === 'granted'; } return true; } 递归遍历与读取async function* walkDir(dirHandle, base = '') { for await (const [name, handle] of dirHandle.entries()) { const path = base ? `${base}/${name}` : name; if (handle.kind === 'file') { yield { path, handle }; } else if (handle.kind === 'directory') { yield* walkDir(handle, path); } } } async function readAllText(dirHandle) { const out = {}; for await (const { path, handle } of walkDir(dirHandle)) { const file = await handle.getFile(); out[path] = await file.text(); } return out; } 选择器入口与降级async function pickAndReadAll() { if (!supportsDirPicker) throw new Error('directory picker unsupported'); const dir = await window.showDirectoryPicker(); const ok = await requestPerm(dir, 'read'); if (!ok) throw new Error('permission denied'); return readAllText(dir); }

发表评论 取消回复