Core idea
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 querying databases.
Blocking code waits for an operation to finish before executing the next statement. Non-blocking code starts the operation and continues executing other code while the operation completes in the background.
How Node.js handles I/O
- A request enters the application and reaches JavaScript code.
- Synchronous I/O blocks the current flow until the resource responds.
- Asynchronous I/O delegates waiting work to the Node.js runtime and resumes through a callback, promise, or async function.
- This model helps Node.js handle many concurrent requests without creating one thread per request.
Blocking 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.
Example: 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");
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. When the I/O finishes, Node.js runs the callback or resolves the promise.
Example: 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");
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() |