Read and write text files
Local practice: Node.js 22.16.0 and npm 10.9.2 on Linux x64; proposed teaching baseline 26.13.1 LTS remains untested. Use a fresh disposable folder for each example, copy only the shown files and run the fixed command. No packages or external services required. Static examples are not ByteMind runner support. The archive is author-only; do not copy expected.json into the example directory.
Write and read an owned text file
import { mkdtempSync, writeFileSync, readFileSync, unlinkSync, rmdirSync } from "node:fs";import { join } from "node:path";const dir = mkdtempSync("report-");const file = join(dir, "note.txt");try { writeFileSync(file, "Stock: 4\n", { encoding: "utf8", flag: "wx" }); console.log(readFileSync(file, "utf8").trim());} finally { try { unlinkSync(file); } catch (e) { if (e.code !== "ENOENT") throw e; } rmdirSync(dir);}Run in this fixture directory:
node main.mjsExpected stdout:
Stock: 4Expected exit status: 0. Expected stderr: empty. Exclusive creation avoids overwriting. The finally block removes only the owned path.
How it works
readFileSync(path, "utf8") returns decoded text; without an encoding it returns a Buffer. writeFileSync writes the supplied text or bytes and by default may truncate an existing file. flag: "wx" creates a new file exclusively and fails if it already exists. Keep examples in a new disposable directory with fixed synthetic names. The snippets use a generated subdirectory and remove only the known file and directory in finally. File operations can fail for missing paths, permissions or storage errors. Use the actual error code to decide whether to recover or rethrow.
Inspect a missing-file error
import { readFileSync } from "node:fs";try { readFileSync("absent-demo.txt", "utf8"); }catch (error) { if (error.code !== "ENOENT") throw error; console.log("No report yet");}Run in this fixture directory:
node main.mjsExpected stdout:
No report yetExpected exit status: 0. Expected stderr: empty. The fresh fixture contains no file by that name, so ENOENT is handled explicitly.
Common mistake
Do not use a broad recursive delete or permission change to make a file example pass. Never assume a check for existence guarantees a later write is safe; another process may change the state between operations.
Try it yourself
Change the synthetic title, write it as UTF-8, and read it back. Try writing a second time with wx, predict the error code, and keep the original file unchanged.
Further reading: Official documentation 1. Related ByteMind reference candidate: node-fs-readfilesync (route not verified).
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Read and write text files — knowledge check
Apply the concepts and predict the behavior taught in this lesson.
What does readFileSync return without an encoding?
Which flag requests exclusive creation?
What does ENOENT commonly indicate?