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.

JavascriptCli Tooling

Code

javascriptsnippet
19 lines
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: removed

Inside 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

FAQ

Are there third-party dependencies?
No. The imports resolve to Node.js core modules, which the runtime provides.