FileHandle Read Loop With Reused Buffer
Read a file through one reused buffer with FileHandle.read: each call reports its byte count and a zero read marks end of file.
Code
import { open, writeFile, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
// Reading with one reused buffer avoids allocating a chunk per read;
// read() reports how many bytes landed, and 0 means end of file.
const source = join(tmpdir(), `scan-${process.pid}.txt`);
await writeFile(source, "batch-01\nbatch-02\nbatch-03\n", "utf8");
const handle = await open(source, "r");
const buffer = Buffer.alloc(8);
let text = "";
let bytesRead = 1;
let reads = 0;
while (bytesRead > 0) {
const result = await handle.read(buffer, 0, buffer.length, null);
bytesRead = result.bytesRead;
reads += 1;
if (bytesRead > 0) text += buffer.toString("utf8", 0, bytesRead);
}
await handle.close();
console.log("reads:", reads, "| lines:", text.trim().split("\n").length);
console.log("content intact:", text.trim() === "batch-01\nbatch-02\nbatch-03");
await rm(source, { force: true });Output
Captured from a sandboxed run of this snippet in the build pipeline.
reads: 4 | lines: 24
content intact: trueHow the snippet works
Iteration happens inside while (bytesRead > 0) — everything outside it runs once. Every asynchronous step is awaited, so rejections surface where the call happens. The import names the platform contact area: open, writeFile, rm, tmpdir, join, all from node:fs/promises, node:os, node:path.
Top-level bindings source, handle, buffer, text hold the demo state — nothing sits inside a function scope.
What to watch for
node:fs/promisesis a Node.js built-in module — it ships with the runtime, so there is nothing to install.
Using it
The demo output is labeled (reads:, content intact:); each label names the call that printed it.
Key statements
await writeFile(source, "batch-01\nbatch-02\nbatch-03\n", "utf8");
const result = await handle.read(buffer, 0, buffer.length, null);
if (bytesRead > 0) text += buffer.toString("utf8", 0, bytesRead);
Interactive Tools for This Topic
FAQ
- Does this require external packages?
- No — `node:fs/promises` is a Node.js built-in module; nothing to install.
Report a problem with this exampleOpens a pre-filled issue on GitHub.