What is the difference between synchronous and asynchronous code in Node.js?
Answer
Synchronous code executes sequentially — each operation blocks the execution thread until it completes before the next line runs. In Node.js, synchronous operations block the event loop, preventing other requests from being handled. Example: fs.readFileSync("file.txt") — the thread waits until the file is fully read. Asynchronous code initiates an operation and immediately continues executing other code. When the operation finishes, a callback, promise resolution, or event notifies Node.js to handle the result. Example: fs.readFile("file.txt", callback) — Node.js registers the callback and moves on; the callback runs later when the file is ready. Rule of thumb: never use synchronous I/O (readFileSync, writeFileSync) in request handlers or any code that runs per-request, as it blocks every other request. Synchronous operations are acceptable in startup/initialization code (before the server starts listening), CLI scripts, or build tools.