What is the difference between blocking and non-blocking code in Node.js, and how do you keep the event loop responsive?
Blocking means the JavaScript thread cannot do anything else until the operation finishes. Non-blocking means the work is handed off and a callback runs when it completes. Because Node serves every request on one thread, one blocking call delays every other user.
What blocks:
- The synchronous
fsmethods —readFileSync,writeFileSyncand friends. - CPU-heavy work: hashing with a high cost factor, image resizing, large
JSON.parse, sorting a huge array, complex regular expressions on long strings. child_process.execSync.
How to keep the loop free:
- Use the promise-based
fsAPI for anything on a request path. Sync calls are acceptable only at startup. - Move CPU-bound work to
worker_threads, or to a queue consumed by a separate process. - Break long loops into chunks that yield with
setImmediate. - Stream large payloads rather than buffering them.
Note: Say how you would detect it. Measuring event loop lag — with perf_hooks monitorEventLoopDelay or a simple timer drift check — and alerting on it is what turns this from theory into operations.





