实现说明
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 });