filesystem
import { mkdtempSync, writeFileSync, readFileSync, rmSync } from "node:fs";
import { join } from "node:path";
import { tmpdir } from "node:os";
const dir = mkdtempSync(join(tmpdir(), "tool-"));
const file = join(dir, "note.txt");
writeFileSync(file, "payload\n");
console.log(readFileSync(file, "utf8"));
rmSync(dir, { recursive: true, force: true });
Output:
payload
Why temp directories
Write into a directory created for this run
Do not write beside the source file
Cleanup becomes one rmSync call instead of a hunt for leftovers
Sync versus async
The Sync variants block the event loop
They are fine in a short script or at startup
They are wrong in a server request path
The async variants live in node:fs/promises
import { readFile } from "node:fs/promises";
const text = await readFile("note.txt", "utf8");
Paths
Resolve user supplied paths against a known base Reject anything that escapes it A file read primitive with an untrusted path is a traversal bug
Next
Large data in 05 streams
Posted