← 中文资源

简体中文版本

FileHandle.read 复用缓冲循环

用同一个 buffer 反复 FileHandle.read 直到读到 0 字节(EOF):每次都报告实际字节数,27 字节内容 8 字节缓冲恰好 5 次读完。

阅读英文原文

运行结果

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

reads: 4 | lines: 24
content intact: true

实现说明

驱动整个流程的是 while (bytesRead > 0) 这一个循环。每个异步步骤都被 await,拒绝会在发起调用的那一行浮出。导入清单标出了平台接触面:open、writeFile、rm、tmpdir、join,全部来自 node:fs/promises、node:os、node:path。 source、handle、buffer、text 定义在模块顶层,中间不经过函数作用域。

使用要点

  • 依赖面只有 node:fs/promises,而它内置于 Node.js。
  • 演示输出是带标签的(reads:、content intact:),每个操作都会留下自己的一行标注。

常见问题

需要安装第三方包吗?

不需要——node:fs/promises 是 Node.js 内建模块,无需安装。

核心语句

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);

代码示例

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 });