What is the difference between synchronous and asynchronous programming in Node.js? Why is fs.readFileSync fine in a start-up script but harmful inside a request handler?
Show the explanation
Model answer.
- Synchronous code runs step by step; each line waits for the previous one to finish. A slow step blocks everything after it.
- Asynchronous code starts an operation and continues; the result arrives later via a callback, a promise or
await, while the thread serves other work.
// blocking: the whole server pauses while the file is read
app.get('/report', (req, res) => res.send(fs.readFileSync('big.csv', 'utf8')));
// non-blocking: other requests are served while the file loads
app.get('/report', async (req, res, next) => {
try { res.send(await fs.promises.readFile('big.csv', 'utf8')); }
catch (err) { next(err); }
});In a start-up script (loading config once before the server listens), the sync version is simple and harmless, because nothing else is waiting. Inside a request handler, it stalls every concurrent user for as long as the read takes. For very large files, prefer streams, so memory stays flat.
Original UniCircle question. Last reviewed 22 Oct 2026.
