fs.rm Clears Scratch Trees With force And recursive

Remove whole scratch directories with fs.rm recursive, and let force turn missing paths into no-ops so cleanup code is safe to run twice.

JavascriptCli Tooling

Code

javascriptsnippet
18 lines
import { mkdtemp, mkdir, writeFile, rm, readdir } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';

const scratch = await mkdtemp(join(tmpdir(), 'build-'));
await mkdir(join(scratch, 'chunks/a'), { recursive: true });
await mkdir(join(scratch, 'chunks/b'), { recursive: true });
await writeFile(join(scratch, 'manifest.json'), '{}');
await writeFile(join(scratch, 'chunks/a/000.bin'), 'x');

console.log('before:', (await readdir(scratch)).sort());

// recursive deletes subdirectories; force keeps ENOENT from throwing.
await rm(scratch, { recursive: true, force: true });

// Safe to repeat: force makes the second call succeed on a missing path.
await rm(scratch, { recursive: true, force: true });
console.log('after cleanup: gone');

Output

Captured from a sandboxed run of this snippet in the build pipeline.

before: [ 'chunks', 'manifest.json' ]
after cleanup: gone

What the code does

The async parts await their results, which keeps ordering predictable. node:fs/promises, node:os, node:path supplies mkdtemp, mkdir, writeFile, rm, readdir — built-in surface, no package involved.

The file’s state is a handful of top-level bindings: scratch.

What to watch for

  • node:fs/promises is a Node.js built-in module — it ships with the runtime, so there is nothing to install.

Applying it

The demo output is labeled (before:, after cleanup: gone), so every printed line maps back to its originating operation.

Statements that matter

await mkdir(join(scratch, 'chunks/a'), { recursive: true });
await mkdir(join(scratch, 'chunks/b'), { recursive: true });
const scratch = await mkdtemp(join(tmpdir(), 'build-'));

Interactive Tools for This Topic

FAQ

What does this import from outside the project?
Only `node:fs/promises`, and that is a Node.js built-in — it comes with the runtime.