Node.js
Create an isolated temporary directory
Use mkdtemp with a prefix inside the operating system’s temporary directory. Keep the returned path and remove that exact directory after the operation has finished.
Worked example
Node.js example · save as example.mjs and run node example.mjs
import * as fs from "node:fs/promises";
import {tmpdir} from "node:os";
import {join} from "node:path";
const directory = await fs.mkdtemp(join(tmpdir(), "file-guide-"));
try {
const files = await fs.readdir(directory);
console.log(files.length);
await fs.writeFile(join(directory, "scratch.txt"), "temporary");
console.log((await fs.readdir(directory)).includes("scratch.txt"));
} finally {
await fs.rm(directory, {recursive: true, force: true});
}How it works
The surrounding setup uses mkdtemp to create the directory with a unique suffix. A try/finally block removes the same returned directory even when the example body throws. This keeps one run from colliding with another run’s scratch files.
Limits and mistakes
Temporary storage is not a persistence guarantee. Do not construct a cleanup target from unchecked user input or delete a shared parent directory. File contents may remain accessible according to operating-system permissions until cleanup completes.
Check the result
Expect 0 and true. Force an error after the write in a disposable run and confirm finally still removes the created directory.
Sources
Reference documentation for the behavior used in this guide: