Difference Between Blocking and Non-Blocking in Node.js
In Node.js, blocking and non-blocking describe how the program handles I/O operations such as reading files, writing files, making network requests, or interacting with databases.
Quick definition
In Node.js, blocking and non-blocking describe how the program handles I/O operations such as reading files, writing files, making network requests, or interacting with databases.
How Blocking and Non-Blocking I/O Flow Through Node.js
Flow diagram
Requests enter the event queue, the event loop coordinates work, and I/O can either block the current flow or complete asynchronously.
flowchart LR
A[Request] --> B[Event Queue]
B --> C[Event Loop]
C --> D{I/O Operation}
D -->|Synchronous| E[Blocking Operation]
E --> F[External Resource]
F --> C
D -->|Asynchronous| G[Non-Blocking Operation]
G --> H[I/O Polling]
H --> CBlocking in Node.js
Blocking code runs in a way that pauses the program until the current task is finished. The next line of code does not run until the task is complete.
const fs = require("fs");
console.log("Before reading file");
const data = fs.readFileSync("file.txt", "utf8");
console.log("File content:", data);
console.log("After reading file");Here, the program waits for the file to be read before moving to the next statement.
Non-Blocking in Node.js
Non-blocking code does not pause the program. It starts the task and immediately moves to the next line of code.
const fs = require("fs");
console.log("Before reading file");
fs.readFile("file.txt", "utf8", (err, data) => {
if (err) {
console.error("Error reading file");
return;
}
console.log("File content:", data);
});
console.log("After reading file");Here, the program continues running while the file is being read in the background.
Difference Between Blocking and Non-Blocking
| Blocking Operations | Non-Blocking Operations |
|---|---|
| Wait for the task to finish. | Continue immediately after starting the task. |
| Stop the current flow of execution. | Keep the flow of execution moving. |
| Use synchronous functions. | Use asynchronous functions. |
| Can delay the application. | Keeps the application responsive. |
| Better for simple scripts. | Better for I/O-heavy applications. |
| Example: readFileSync() | Example: readFile() |
Interview Explanation
- Blocking means Node.js waits for the operation to complete before it continues.
- Non-blocking means Node.js delegates waiting work and continues handling other tasks.
- In a server, blocking I/O can delay every request handled by that process.
- Non-blocking I/O improves concurrency because Node.js can serve other requests while waiting for files, network calls, or database responses.
Compact Interview Questions
What is the difference between blocking and non-blocking in Node.js?
Blocking code waits for an operation to complete before continuing. Non-blocking code starts the operation, continues execution, and handles the result later through a callback, promise, or async/await.