mkdir Recursive Scaffolds Directory Trees
Create nested output folders in one call with recursive:true, repeat the call safely on existing paths, then drop the whole tree with rm recursive and force.
Code
import { mkdir, readdir, rm, writeFile } from 'node:fs/promises';
// recursive:true creates every missing parent and does not throw EEXIST
await mkdir('reports/2026-11/logs', { recursive: true });
await writeFile('reports/2026-11/logs/run-1.log', 'ok\n');
// Calling it again on an existing path is a no-op, not an error
await mkdir('reports/2026-11/logs', { recursive: true });
console.log('tree:', (await readdir('reports', { recursive: true })).join(' | '));
// rm with recursive and force removes nested trees and tolerates paths
// that are already gone — the follow-up readdir must handle ENOENT
await rm('reports', { recursive: true, force: true });
const gone = await readdir('reports').then(
() => 'still there',
() => 'removed',
);
console.log('after rm:', gone);Output
Captured from a sandboxed run of this snippet in the build pipeline.
tree: 2026-11 | 2026-11\logs | 2026-11\logs\run-1.log
after rm: removedInside the snippet
Await points sequence the asynchronous work; a rejection lands at the awaiting line. The only import source is node:fs/promises, a Node.js built-in, exposing mkdir, readdir, rm, writeFile.
Top-level bindings gone hold the demo state — nothing sits inside a function scope.
What to watch for
- The only import,
node:fs/promises, is part of the Node.js standard library.
Using it
Output lines are prefixed (tree:, after rm:), making each step’s effect easy to spot.
Key statements
const gone = await readdir('reports').then(
() => 'still there',
() => 'removed',
);
await writeFile('reports/2026-11/logs/run-1.log', 'ok\n');
await mkdir('reports/2026-11/logs', { recursive: true });
Interactive Tools for This Topic
Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
FAQ
- Are there third-party dependencies?
- No. The imports resolve to Node.js core modules, which the runtime provides.
Report a problem with this exampleOpens a pre-filled issue on GitHub.