The File System (fs)
Read and write files on the server — something the browser can never do.
What you will learn
- Read and write files with fs
- Use asynchronous file methods
- Understand why async matters
Working with files
The fs (file system) module reads and writes files on the server’s disk — something a browser is never allowed to do. Prefer the asynchronous methods so your server never freezes while waiting for the (slow) disk. Async fs methods take a callback — a function Node runs later, once the file work is done. That callback’s first argument is always an error (err), which is null if everything went fine.
The example below does two things in order — write a file, then read it back:
fs.writeFilesaves the text"Hello, file!"intonote.txt(creating the file if it does not exist).- When the write finishes, Node calls its callback — we check
errand log a success message. fs.readFileopensnote.txtand reads its contents.- When the read finishes, its callback receives the file’s text as
data, which we print.
const fs = require("fs");
// Write a file
fs.writeFile("note.txt", "Hello, file!", (err) => {
if (err) throw err;
console.log("File written.");
});
// Read a file
fs.readFile("note.txt", "utf8", (err, data) => {
if (err) throw err;
console.log("File says:", data);
});Note: Output:
File written.
File says: Hello, file!
The "utf8" in readFile tells Node to give you readable text rather than raw bytes. if (err) throw err means "if something went wrong, stop and show the error". Note both operations run asynchronously, so the exact order can vary — but here the write finishes first, then the read prints what was saved.
Note: There are also synchronous versions (readFileSync) that are simpler but block everything until done. Use them only for quick scripts, never inside a busy server.
Tip: Modern Node also offers promise-based file methods (fs.promises) so you can use async/await — cleaner than callbacks.
Q. Why prefer the asynchronous fs methods in a server?
✍️ Practice
- Write a script that saves some text to a file and then reads it back.
- Append a new line to an existing file.
🏠 Homework
- Build a tiny “notes” script that writes user-provided text to a file.