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.
Code
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: goneWhat 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/promisesis 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
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
- 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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.