Opendir Async Iteration Of Entries

Stream directory entries one at a time with opendir's async iterator; the Dir auto-closes after a complete pass, so later reads throw ERR_DIR_CLOSED.

JavascriptCli Tooling

Code

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

Output

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

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

How it works

for await (const entry of dir) is the loop that carries the per-item work. Every asynchronous step is awaited, so rejections surface where the call happens. The import names the platform contact area: mkdtemp, opendir, rm, writeFile, tmpdir, all from node:fs/promises, node:os, node:path.

The file’s state is a handful of top-level bindings: workdir, dir, jsonFiles.

Watch out for

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

Putting it to use

Output lines are prefixed (json files:, read after iteration throws:), so the tagged lines keep each step’s outcome on display.

Core lines

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

Interactive Tools for This Topic

FAQ

What does this import from outside the project?
Only `node:fs/promises`, and that is a Node.js built-in — it comes with the runtime.