typestar

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

  1. withFileTypes avoids a stat call per entry.
  2. recursive: true walks the whole tree.
  3. stat gives size and modification time.

Keywords and builtins used here

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.

Type this snippet

Step 2 of 2 in Files, step 4 of 18 in Node.js.

← Previous Next →

Walking a directory in other languages