Last Updated : 23 Jul, 2025
In NodeJS, blocking and non-blocking are two ways of writing code. Blocking code stops everything else until it's finished, while non-blocking code lets other things happen while it's waiting. This difference is key to understanding how NodeJS works and writing fast, efficient applications.
What is Blocking?Blocking in NodeJS means that when your code runs a task, it stops and waits for that task to completely finish before moving on to the next thing. It's like reading a book one word at a time, never skipping ahead.
function myFunction() {
console.log("Starting a task...");
// Simulate a long-running task (blocking)
let sum = 0;
for (let i = 0; i < 1000000000; i++) { // A big loop!
sum += i;
}
console.log("Task finished!");
return sum;
}
console.log("Before the function call");
let result = myFunction();
console.log("After the function call");
console.log("Result:", result);
Output
Blocking Operation in NodeJS What is Non-Blocking?Non-blocking means your program can keep doing other things while a task is running in the background. It doesn't have to stop and wait for that task to finish before moving on.
function myFunction() {
console.log("Starting a task...");
// Simulate a long-running task (non-blocking) - using setTimeout
setTimeout(() => {
let sum = 0;
for (let i = 0; i < 1000000000; i++) { // A big loop!
sum += i;
}
console.log("Task finished!");
console.log("Result:", sum);
}, 0); // The 0 delay makes it asynchronous
}
console.log("Before the function call");
myFunction(); // The program doesn't wait here
console.log("After the function call");
Output
Non Blocking Operation in NodeJS Difference Between Blocking and Non-BlockingHere's a table which shows the key differences between blocking and non-blocking operations
Feature Blocking Operations Non-Blocking Operations Execution Waits until the operation completes. Continues immediately; operation completes later. Thread Behavior Current thread waits (is blocked). Current thread continues; operation handled separately. Resource Usage Easier to implement but may waste resources while waiting. More complex but uses resources more efficiently. Responsiveness Can cause delays if operations are slow. Keeps application responsive during long operations. Use Cases Simple tasks where waiting is acceptable. Tasks requiring high responsiveness, like user interfaces. Complexity Easier to implement. Requires managing callbacks or async mechanisms. Examples Reading a file entirely before proceeding. Starting a file read and continuing without waiting. Error Handling Errors handled immediately after the operation. Errors handled later, often in callbacks or error handlers. Real-World ExamplesLet's see how blocking and non-blocking I/O work with web servers. This will show why non-blocking is so much better, especially in NodeJS.
Blocking HTTP ServerA blocking server handles one request at a time. If it's busy reading a file for one user, other users have to wait.
const http = require('http');
const fs = require('fs');
http.createServer((req, res) => {
const data = fs.readFileSync('largeFile.txt', 'utf8'); // Blocking!
res.end(data);
}).listen(3000);console.log("Server running at http://localhost:3000/");
A non-blocking server can handle many requests at the same time. If it needs to read a file, it starts the read and then goes back to handling other requests. When the file is ready, the server is told about it and then it can send the data to the user.
const http = require('http');
const fs = require('fs');http.createServer((req, res) => {
fs.readFile('largeFile.txt', 'utf8', (err, data) => { // Non-blocking!
if (err) {
res.writeHead(500);
res.end("Error reading file");
return;
}
res.end(data);
});
}).listen(3000);console.log("Server running at http://localhost:3000/");
NodeJS handles non-blocking I/O using
NodeJS is single-threaded, but it achieves concurrency through the event loop, which efficiently handles non-JavaScript operations, such as I/O tasks. Callback functions are sent to the event loop and executed only after other operations are completed.
Combining blocking and non-blocking code can cause issues, such as operations executing before their dependencies are complete. For example, trying to print file content before it has been fully read.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4