Durable Writes With FileHandle Sync

Force file data to stable storage with FileHandle.sync, reopen with datasync for a metadata-free flush, and read the bytes back.

JavascriptData Integrity

Code

javascriptsnippet
20 lines
// 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 });

Output

Captured from a sandboxed run of this snippet in the build pipeline.

bytes persisted: 29

What the code does

The asynchronous flow is linearized with await, keeping failure handling local. The only import source is node:fs/promises, node:os, node:path, a Node.js built-in, exposing open, rm, readFile, tmpdir, join.

Demo state sits in top-level bindings: target, payload, handle, reopen.

What to watch for

  • node:fs/promises is a Node.js built-in module — it ships with the runtime, so there is nothing to install.

Using it

Output lines are prefixed (bytes persisted:), so each printed line announces the step behind it.

Key statements

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

Interactive Tools for This Topic

FAQ

Do I need to install anything before running this?
Nothing needs installing: `node:fs/promises` ships with Node.js itself.