← 中文资源

简体中文版本

opendir 的异步条目迭代

用 opendir 返回的 Dir 异步迭代器逐条读取目录项,不必一次性载入全部列表;完整迭代后目录自动关闭,再读会抛 ERR_DIR_CLOSED。

阅读英文原文

运行结果

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

json files: [ 'batch-001.json', 'batch-002.json' ]
read after iteration throws: ERR_DIR_CLOSED

实现说明

for await (const entry of dir) 反复执行,循环体之外没有别的重复。异步流被 await 线性化,失败处理保持局部。mkdtemp、opendir、rm、writeFile、tmpdir 来自 node:fs/promises、node:os、node:path——Node.js 随运行时自带的核心模块。 顶层就这几处状态:workdir、dir、jsonFiles。

使用要点

  • 唯一的导入 node:fs/promises 属于 Node.js 标准库。
  • 直接运行文件,输出会带上标签,比如 json files:、read after iteration throws:——输出的每一行都能指回产生它的那次调用。

常见问题

它从项目之外导入了什么?

只有 node:fs/promises,而它是 Node.js 内建的——随运行时提供。

核心语句

const workdir = await mkdtemp(join(tmpdir(), "ingest-"));
await writeFile(join(workdir, "batch-001.json"), "{}");
await writeFile(join(workdir, "batch-002.json"), "{}");

代码示例

import { mkdtemp, opendir, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";

// opendir() returns a Dir whose async iterator streams entries one at a time
// instead of materializing the whole listing in memory.
const workdir = await mkdtemp(join(tmpdir(), "ingest-"));
await writeFile(join(workdir, "batch-001.json"), "{}");
await writeFile(join(workdir, "batch-002.json"), "{}");
await writeFile(join(workdir, "notes.txt"), "skip me");

const dir = await opendir(workdir);
const jsonFiles = [];
for await (const entry of dir) {
  if (entry.isFile() && entry.name.endsWith(".json")) {
    jsonFiles.push(entry.name);
  }
}
console.log("json files:", jsonFiles.sort());

// Completing the iteration closes the directory automatically
try {
  await dir.read();
} catch (err) {
  console.log("read after iteration throws:", err.code);
}

await rm(workdir, { recursive: true, force: true });