← 中文资源

简体中文版本

OPFS 私有文件区读写

navigator.storage.getDirectory 打开各 origin 私有且持久的文件区:createWritable 写入、getFile 读回、estimate 汇报配额用量。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

OPFS needs a browser with navigator.storage.getDirectory

实现说明

真正干活的是函数 usage,其余都是接线。 每个异步步骤都被 await,拒绝会在发起调用的那一行浮出。

使用要点

  • 浏览器才是这里的运行环境:navigator 在 Node 里拿不到。

常见问题

除了语言运行时还需要什么准备?

什么都不需要——语言运行时是唯一要求。 文件在加载时定义 usage。

主签名形如 const usage = (await navigator.storage.estimate()

核心语句

const usage = (await navigator.storage.estimate()).usage ?? 0;
await writable.write(JSON.stringify({ step: 3, of: 5 }));
const readBack = await (await root.getFileHandle("progress.json")).getFile();

代码示例

// OPFS (origin-private file system) gives each origin a private, persistent
// file area: navigator.storage.getDirectory() returns the root handle.
if (typeof navigator === "undefined" || !navigator.storage?.getDirectory) {
  console.log("OPFS needs a browser with navigator.storage.getDirectory");
} else {
  const root = await navigator.storage.getDirectory();
  const handle = await root.getFileHandle("progress.json", { create: true });
  const writable = await handle.createWritable();
  await writable.write(JSON.stringify({ step: 3, of: 5 }));
  await writable.close();

  const readBack = await (await root.getFileHandle("progress.json")).getFile();
  console.log("stored:", await readBack.text());

  const usage = (await navigator.storage.estimate()).usage ?? 0;
  console.log("quota usage reported:", usage >= 0);
}