← 中文资源

简体中文版本

用 FileHandle.sync 做持久写

writeFile 只把数据交给操作系统,不保证落盘:FileHandle.sync 强制刷盘,datasync 只刷数据跳过元数据更省开销,最后回读字节数验证。

阅读英文原文

运行结果

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

bytes persisted: 29

实现说明

异步部分依次 await 结果,顺序可预测。open、rm、readFile、tmpdir、join 来自 node:fs/promises、node:os、node:path——Node.js 随运行时自带的核心模块。 演示用的数据放在这几个模块级绑定中:target、payload、handle、reopen。

使用要点

  • 唯一的导入 node:fs/promises 属于 Node.js 标准库。
  • 每一步打印都带着自己的标签:bytes persisted:。

常见问题

运行之前需要装什么吗?

什么都不用装:node:fs/promises 随 Node.js 本体提供。

核心语句

const payload = JSON.stringify({ checkpoint: 41, items: 128 });
await handle.writeFile(payload, "utf8");
const reopen = await open(target, "r+");

代码示例

// Durable writes: a plain writeFile hands data to the OS but does not force
// it to disk; handle.sync() flushes file contents, datasync() skips metadata.
import { open, rm, readFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";

const target = join(tmpdir(), `durable-${process.pid}.json`);
const payload = JSON.stringify({ checkpoint: 41, items: 128 });

const handle = await open(target, "w");
await handle.writeFile(payload, "utf8");
await handle.sync();
await handle.close();

const reopen = await open(target, "r+");
await reopen.datasync();
await reopen.close();

console.log("bytes persisted:", (await readFile(target, "utf8")).length);
await rm(target, { force: true });