Reading and writing files in JavaScript
The promises API, awaited, with real errors.
import { mkdtemp, readFile, writeFile, appendFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
const dir = await mkdtemp(join(tmpdir(), "typestar-"));
const path = join(dir, "runs.txt");
await writeFile(path, "go 104\n", "utf8");
await appendFile(path, "rust 98\n", "utf8");
const text = await readFile(path, "utf8");
console.log(text.trimEnd().split("\n"));
try {
await readFile(join(dir, "missing.txt"), "utf8");
} catch (error) {
console.log(error.code, error instanceof Error);
}
How it works
fs/promisesis the modern surface; the callback one is legacy.writeFilereplaces,appendFileadds.- A missing file rejects with a code of ENOENT.
Keywords and builtins used here
awaitcatchconstfromimporttry
The run, in numbers
- Lines
- 18
- Characters to type
- 537
- Tokens
- 135
- Three-star pace
- 100 tpm
At the three-star pace of 100 tokens a minute, this run takes about 81 seconds.
Step 1 of 2 in Files, step 3 of 18 in Node.js.