概述通过估算配额与遍历文件元数据,可以实现自动清理策略以避免空间占满。监控与清理async function estimate() { return navigator.storage.estimate(); } async function walk(dir, base, onFile, onDir) { for await (const [name, h] of dir.entries()) { const p = base ? base + '/' + name : name; if (h.kind === 'file') { await onFile(h, p); } else { const sub = await dir.getDirectoryHandle(name); onDir && (await onDir(sub, p)); await walk(sub, p, onFile, onDir); } } } async function cleanup(thresholdRatio = 0.8) { const { usage, quota } = await estimate(); if (usage / quota < thresholdRatio) return; const root = await navigator.storage.getDirectory(); const list = []; await walk(root, '', async (fh, path) => { const f = await fh.getFile(); list.push({ path, size: f.size, ts: f.lastModified }); }); list.sort((a,b) => a.ts - b.ts); for (const x of list.slice(0, Math.ceil(list.length * 0.2))) { const seg = x.path.split('/'); let d = root; for (let i=0;i<seg.length-1;i++) d = await d.getDirectoryHandle(seg[i]); await d.removeEntry(seg[seg.length-1]); } }

发表评论 取消回复