Node.jsbeginner 8 min
Read and write files with the fs module, using async and await.
How to write text to a file and read it back using node:fs/promises.
Reading config, saving logs and processing uploads all mean touching the file system, something browsers are not allowed to do freely.
Node's fs module has file functions. The promise version is the modern way, imported from node:fs/promises. It works nicely with async and await:
await writeFile(path, text): create or overwrite a file.await readFile(path, "utf8"): read it as text.await appendFile(path, text): add to the end.await unlink(path): delete a file.await pauses that function until the operation finishes, without freezing the rest of the program. At the top level of an ES module you can use await directly.
Save as files.mjs:
writeFile creates note.txt containing Buy milk.appendFile adds a second line.readFile returns the whole file as a string. Printing it shows both lines.unlink deletes the file so the script leaves no mess.Run it on your machine, then change the script so that it keeps the file and reads it again on the next run.
await, so you get a Promise instead of the file text."utf8" and getting a Buffer of bytes.try / catch.node, not to the script.node:fs/promises with await.writeFile, readFile, appendFile and unlink cover most needs.try / catch.Next: your first web server.
import { writeFile, readFile, appendFile, unlink } from "node:fs/promises";
await writeFile("note.txt", "Buy milk\n");
await appendFile("note.txt", "Call Ravi\n");
const text = await readFile("note.txt", "utf8");
console.log(text);
const lines = text.trim().split("\n");
console.log("Lines:", lines.length);
await unlink("note.txt");