实现说明
异步部分依次 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 });