概述File System Access API 提供用户授权下的文件读写。本文通过时间戳校验与安全写入策略降低并发覆盖风险。能力与权限const supportsFSA = typeof window.showOpenFilePicker === 'function'; async function ensurePermission(handle, mode = 'readwrite') { if (typeof handle.requestPermission === 'function') { const s = await handle.requestPermission({ mode }); return s === 'granted'; } return true; } 冲突检测与安全写入async function writeIfUnchanged(fileHandle, content, expectedLastModified) { const ok = await ensurePermission(fileHandle, 'readwrite'); if (!ok) throw new Error('permission denied'); const current = await fileHandle.getFile(); if (expectedLastModified && current.lastModified !== expectedLastModified) { throw new Error('conflict detected'); } const ws = await fileHandle.createWritable(); await ws.write(content); await ws.close(); } async function safeUpdateByPicker(updater) { const [handle] = await window.showOpenFilePicker({ multiple: false }); const file = await handle.getFile(); const newContent = await updater(await file.text()); await writeIfUnchanged(handle, newContent, file.lastModified); } 注意事项将写入绑定到明确的用户交互事件以提升权限通过率。使用 `getFile().lastModified` 做并发校验,避免跨窗口覆盖。大文件建议改为分块或流式写入以降低阻塞。

发表评论 取消回复