What is the difference between fs.readFileSync, fs.readFile and fs.promises.readFile?
readFileSync blocks the thread until done. readFile takes a callback and does not block. fs.promises.readFile returns a promise for use with await. In servers, prefer the non-blocking forms.
Explain it simply
Ordering a parcel: with the sync version you stand at the gate doing nothing until it arrives. With the callback version you go back to work and the guard calls you when it is here. The promise version is the same as the callback one, except you get a token you can await.
Example
const fs = require("fs");
const fsp = require("fs/promises");
// 1. blocks everything until the file is read
const a = fs.readFileSync("notes.txt", "utf8");
// 2. non-blocking, error-first callback
fs.readFile("notes.txt", "utf8", (err, data) => {
if (err) return console.error(err.code);
console.log(data.length);
});
// 3. non-blocking, awaitable
async function load() {
const data = await fsp.readFile("notes.txt", "utf8");
return data;
}When each one fits:
- Sync: start-up scripts, CLI tools, reading config once before the server listens.
- Callback or promise: anything inside a request handler or other hot path.
Without the encoding argument ("utf8") you receive a Buffer, not a string. All three read the entire file into memory, so for very large files use a stream.
What to say in the interview
"Sync blocks the event loop, so I use it only at start-up. In request handlers I use fs/promises with await. For big files I switch to streams so memory stays flat."
Common mistakes
- Using
readFileSyncinside an Express route. - Forgetting the encoding and printing a Buffer.