fs.readFileSync vs fs.readFile
grasp of blocking vs non-blocking I/O.
sync blocks the event loop and returns directly, async takes a callback or promise, only sync is safe at startup.
using readFileSync inside a request handler.
WHAT THIS TESTS This checks if you understand Node's single-threaded event loop and why blocking operations are dangerous in a server. A candidate who treats sync and async as interchangeable does not grasp Node's concurrency model.
A GOOD ANSWER COVERS fs.readFileSync runs synchronously: it blocks the calling thread until the file is fully read, then returns the buffer or throws an error you catch with try/catch. fs.readFile is asynchronous: it returns immediately and delivers the result later through a callback, or through a promise when you use fs.promises.readFile. Because Node serves all requests on one event loop thread, a synchronous read pauses every other pending request and timer for the duration of the disk operation. You choose sync only for one-time setup at process start, such as loading a config file before the server begins listening, where blocking is harmless. You choose async for anything that runs while serving traffic.
COMMON WRONG ANSWERS Saying the only difference is callback style, or that sync is fine because it is simpler. Another mistake is claiming the operating system handles concurrency for you, ignoring that JavaScript execution itself is single-threaded.
LIKELY FOLLOW-UPS How does the libuv thread pool serve async file I/O. What is the difference between readFile and createReadStream for large files. How do you convert callback APIs to promises with util.promisify.
ONE CONCRETE EXAMPLE A server calls fs.readFileSync on a 50MB file inside a route handler. Under load, every incoming request queues behind that read; throughput collapses and latency spikes for all clients. Switching to await fs.promises.readFile lets the event loop keep accepting and dispatching other requests while the disk read proceeds in the background thread pool.
Read the original → nodejs.org
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.