typestar

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

  1. fs/promises is the modern surface; the callback one is legacy.
  2. writeFile replaces, appendFile adds.
  3. A missing file rejects with a code of ENOENT.

Keywords and builtins used here

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.

Type this snippet

Step 1 of 2 in Files, step 3 of 18 in Node.js.

← Previous Next →

Reading and writing files in other languages