Blocking and Non-Blocking in Node.js

Jessica Mishra
Last Updated: May 13, 2022

Introduction:

There are two types of execution of our code, synchronous and asynchronous. The code is executed in sequence synchronously, and execution is awaited when the function is called. In asynchronous execution, the line is not necessarily followed, and completion of the operation is not necessary. Based on this, we have methods that are blocking and non-blocking in Node.js.

 

In this blog, we will talk about blocking and non-blocking in Node.js.

Blocking:

Blocking means that we are blocking the subsequent operations until the operation is finished. According to Node.js docs, blocking is when the additional Javascript operation is blocked until the non-javascript operation is completed. The blocking method is executed synchronously. That means that the program is executed line by line. 

 

Let us look at an example:

We have used a file here called "sample.text" whose content is "Coding Ninjas".

const fs = require('fs');
 
const filepath = '/uploads/sample.txt';
 
// Reading the file in blocking way
const data = fs.readFileSync(filepath, {encoding: 'utf8'});
 
// Printing the content of file, i.e., "Coding Ninjas"
console.log(data);
 
// Calculating the sum of numbers from 1 to 5
let sum = 0;
for(let i=1; i<=5; i++){
   sum = sum + i;
}
 
// Printing the sum
console.log('Sum: ', sum);

 

Output:

Coding Ninjas!
Sum:  15

If we look at the output, we can see that the sum is printed after all the file contents have been printed. This is because the read file function has been used in a blocking way.

Non-Blocking:

Non-blocking calls are the calls that do not block the execution of other operations. In non-blocking operations, a single process is allowed to serve multiple requests simultaneously. Instead of waiting for completion, functions are delegated to the system to execute the next piece of code.

 

Let us look at an example:

const fs = require('fs');
 
const filepath = '/uploads/sample.txt';
 
// Reading a file in non blocking way
fs.readFile(filepath, {encoding: 'utf8'}, (err, data) => {
   // Printing the content of file
   console.log(data);
});
 
 
// Calculating sum of numbers from 1 to 5
let sum = 0;
for(let i=1; i<=5; i++){
   sum = sum + i;
}
 
// Prints the sum
console.log('Sum: ', sum);

 

Output:

Sum:  15
Coding Ninjas!

 

In this, the file reading operation was performed asynchronously in a non-blocking way. Hence, the sum is printed before the contents of the file.

Comparison between Blocking and Non-Blocking in Node.js:

Non-blocking execution is usually faster if we compare blocking and non-blocking code in node.js, allowing concurrency. It will enable the event loop to execute JavaScript callback functions after completing other operations. 

 

Suppose, if a program takes 40ns to execute and 30ns of that work can be done asynchronously, that frees up 30ns per request handle in which the system can handle other requests.

 

It is not usually a good idea to mix blocking and non-blocking code in node.js:

const fs = require('fs');
fs.readFile('/uploads/sample.txt', (err, data) => {
 if (err) throw err;
 console.log(data);
});
fs.unlinkSync('/uploads/sample.txt');

 

In this code, ‘fs.unlinksync()’ is likely to run first which would delete the sample.txt file before it is read. To avoid this, code can be written in clear non-blocking way:

const fs = require('fs');
fs.readFile('/uploads/sample.txt', (readFileErr, data) => {
 if (readFileErr) throw readFileErr;
 console.log(data);
 fs.unlink('/uploads/sample.txt', (unlinkErr) => {
   if (unlinkErr) throw unlinkErr;
 });
});

 

In this, fs.unlink() is within the callback of fs.callback(), the order of operations will be definite. 

Frequently Asked Questions:

  1. What is a callback in node.js?

Ans-> A callback is a function that is called after the completion of a function. It is used to prevent blocking.

 

2. What is the difference between asynchronous and non-blocking in node.js?

Ans-> Basically, asynchronous improves the performance by doing the task faster, and if the response does not come immediately, other jobs will be performed till we receive it. Non-blocking gives an immediate response if the response is available. Otherwise, it throws an error. 

 

3. Which is faster, blocking or non-blocking in node.js?

Ans-> Non-blocking is usually faster due to concurrency. Since the task can be executed without blocking, time can be saved.

 

4. How can we convert blocking code to non-blocking code?

Ans-> Event loop and callback mechanism move I/O operations from JavaScript thread to the system's kernel. In the kernel, multithreading is used, and multiple requests can be handled easily. When an operation is completed, the kernel informs node.js, and a callback is added to the queue to be executed. Hence, we convert the blocking code into the non-blocking code using callbacks.

Key Takeaways:

This blog talked about blocking and non-blocking in node.js in detail. We compared blocking and non-blocking in node.js according to their performance and discussed some frequently asked questions related to them.

Readers, if you liked this blog on blocking and non-blocking in node.js, you can learn more about Node.js from here.  If you are preparing for your next web development interview, check out the blogs, 25 CSS Interview Questions, and 30 JavaScript interview questions.

Was this article helpful ?
0 upvotes