readdir recursive Option Walks Subtrees
List whole directory trees with readdir({ recursive: true, withFileTypes: true }) and get Dirent objects that carry parentPath for each entry.
Code
import { mkdtemp, mkdir, writeFile, readdir, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
const base = await mkdtemp(join(tmpdir(), 'tree-'));
await mkdir(join(base, 'src/lib'), { recursive: true });
await writeFile(join(base, 'index.js'), 'export {};');
await writeFile(join(base, 'src/lib/util.js'), 'export {};');
// recursive: true walks every level; withFileTypes keeps Dirent objects
const entries = await readdir(base, { recursive: true, withFileTypes: true });
for (const entry of entries) {
console.log(entry.isDirectory() ? 'dir ' : 'file', entry.parentPath, entry.name);
}
await rm(base, { recursive: true, force: true });Output
Captured from a sandboxed run of this snippet in the build pipeline.
file C:\Users\GUANGM~1\AppData\Local\Temp\devex-run-97yId4\tree-JDu8Ad index.js
dir C:\Users\GUANGM~1\AppData\Local\Temp\devex-run-97yId4\tree-JDu8Ad src
dir C:\Users\GUANGM~1\AppData\Local\Temp\devex-run-97yId4\tree-JDu8Ad\src lib
file C:\Users\GUANGM~1\AppData\Local\Temp\devex-run-97yId4\tree-JDu8Ad\src\lib util.jsHow it works
The file repeats itself only inside for (const entry of entries). Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed. node:fs/promises, node:os, node:path supplies mkdtemp, mkdir, writeFile, readdir, rm — built-in surface, no package involved.
Top-level bindings base, entries hold the demo state — nothing sits inside a function scope.
What to watch for
node:fs/promisesis a Node.js built-in module — it ships with the runtime, so there is nothing to install.
Key statements
const entries = await readdir(base, { recursive: true, withFileTypes: true });
await writeFile(join(base, 'src/lib/util.js'), 'export {};');
await mkdir(join(base, 'src/lib'), { recursive: true });
Interactive Tools for This Topic
FAQ
- Does this require external packages?
- No — `node:fs/promises` is a Node.js built-in module; nothing to install.
Report a problem with this exampleOpens a pre-filled issue on GitHub.