背景与价值OPFS 提供站点私有的持久文件系统,无跨站访问风险;同步访问句柄减少读写开销,适合大文件与频繁 IO。获取目录与文件句柄async function getFileHandle(path: string, create = true) { const root = await (navigator as any).storage.getDirectory(); const parts = path.split('/').filter(Boolean); let dir = root; for (let i = 0; i < parts.length - 1; i++) dir = await dir.getDirectoryHandle(parts[i], { create }); return dir.getFileHandle(parts[parts.length - 1], { create }); } 同步访问句柄读写async function writeFile(path: string, data: Uint8Array) { const fh = await getFileHandle(path); const handle = await (fh as any).createSyncAccessHandle(); try { handle.write(data); handle.flush(); } finally { handle.close(); } } async function readFile(path: string) { const fh = await getFileHandle(path, false); const handle = await (fh as any).createSyncAccessHandle(); try { const size = handle.getSize(); const buf = new Uint8Array(size); handle.read(buf); return buf; } finally { handle.close(); } } 并发治理(Web Locks 协同)async function safeWrite(path: string, data: Uint8Array) { await (navigator as any).locks.request(`opfs:${path}`, async () => writeFile(path, data)); } 指标验证(Chrome 128/Edge 130)写入吞吐:较 File System Access 的异步流式写入提升 1.3×–2.1×(场景差异)。稳定性:同步句柄在锁协调下无冲突与损坏;长期读写无泄露。数据保留:与 StorageManager 持久化协同后 30 天保留率 ≥ 99.5%。回退策略不支持 OPFS:回退到 File System Access 的持久句柄或 IndexedDB 存储。测试清单大文件读写:MB–GB 级数据正确;断电与崩溃恢复后数据完整。并发写入:锁协调下顺序正确,无损坏。

点赞(0) 打赏

评论列表 共有 0 条评论

暂无评论
立即
投稿

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部
2.152764s