Dev HelpersOpen library
← Back

Write and read a temporary file

Write and read a temporary file in JavaScript.

Open this example in the interactive library

Source code

import { mkdtemp, readFile, writeFile, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
const dir = await mkdtemp(join(tmpdir(), "helpers-"));
try {
  const file = join(dir, "log.txt");
  await writeFile(file, "Hello");
  console.log(await readFile(file, "utf8"));
} finally {
  await rm(dir, { recursive: true, force: true });
}

Sample output

Hello