Reading and Writing Files
Read a file
Prefer promise-based fs/promises with async/await.
import { readFile } from "fs/promises";
const text = await readFile("notes.txt", "utf8");
console.log(text);
Write a file
Creates the file if missing, or overwrites by default.
import { writeFile } from "fs/promises";
await writeFile("out.txt", "Hello from Node\n", "utf8");
Check existence carefully
Use access or handle errors from read/write. Avoid race-prone exists patterns in servers.
import { access } from "fs/promises";
try {
await access("notes.txt");
console.log("Found");
} catch {
console.log("Missing");
}
Paths matter
Relative paths are relative to the current working directory (where you ran node), not always the script file.
Comments
One comment per signed-in account. Comments are saved with this page’s URL.