Walking a directory in JavaScript
readdir with file types, and the recursive option.
import { mkdir, readdir, stat, writeFile } from "node:fs/promises";
import { mkdtemp } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
const root = await mkdtemp(join(tmpdir(), "walk-"));
await mkdir(join(root, "nested"));
await writeFile(join(root, "a.txt"), "a");
await writeFile(join(root, "nested", "b.txt"), "bb");
const entries = await readdir(root, { withFileTypes: true });
console.log(entries.map((e) => `${e.name}:${e.isDirectory() ? "dir" : "file"}`)
.sort());
const all = await readdir(root, { recursive: true });
console.log(all.length >= 3);
const info = await stat(join(root, "nested", "b.txt"));
console.log(info.size, info.isFile());
How it works
withFileTypesavoids a stat call per entry.recursive: truewalks the whole tree.statgives size and modification time.
Keywords and builtins used here
awaitconstfromimport
The run, in numbers
- Lines
- 19
- Characters to type
- 699
- Tokens
- 199
- Three-star pace
- 100 tpm
At the three-star pace of 100 tokens a minute, this run takes about 119 seconds.
Step 2 of 2 in Files, step 4 of 18 in Node.js.