Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Blocking
3.
Non-Blocking
4.
Comparison between Blocking and Non-Blocking in Node.js
5.
Frequently Asked Questions
5.1.
Is Node JS frontend or backend?
5.2.
What is a callback in node.js?
5.3.
What makes asynchronous and non-blocking in node.js different?
5.4.
Which is faster, blocking or non-blocking in node.js?
5.5.
How can we convert blocking code to non-blocking code?
6.
Conclusion
Last Updated: Mar 27, 2024
Medium

Blocking and Non-Blocking in Node.js

Master Python: Predicting weather forecasts
Speaker
Ashwin Goyal
Product Manager @

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.

Blocking and Non-Blocking in Node.js

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

Blocking

Blocking means 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 "test.txt," whose content is "Blocking and Non-Blocking in Node.js".

Program

const fs = require('fs');
const filepath = '/Users/rashaabdulkhader/Downloads/random/test.txt';
/*
	Reading the file
	in a blocking way
*/
const data = fs.readFileSync(filepath, {encoding: 'utf8'});
/*
	Printing the content 
	of the file, 
	i.e., "Blocking and 
	Non-Blocking in Node.js"
*/
console.log(data);
/*
	Calculating the product 
	of numbers in the array
*/
function product(n) {
	var res = 1;
	for(var i=0;i<n.length;i++) {
		res *=  Number(n[i]);
	}
	return res;
}
console.log(product([5,17,11]));


Output

Output

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

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

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 = '/Users/rashaabdulkhader/Downloads/random/test.txt';
/*
	Reading the file
	in a blocking way
*/
fs.readFile(filepath, {encoding: 'utf8'}, (err, data) => {
	/*
		Printing the content 
		of the file, 
		i.e., "Blocking and 
		Non-Blocking in Node.js"
	*/
	console.log(data);
});
/*
	Calculating the product 
	of numbers in the array
*/
function product(n) {
	var res = 1;
	for(var i=0;i<n.length;i++) {
		res *=  Number(n[i]);
	}
	return res;
}
console.log(product([5,17,11]));


Output

Output

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

Also see, Difference Between Controller and Restcontroller

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 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('FilePathLink', (err, data) => {
	if (err) throw err;
	console.log(data);
});
fs.unlinkSync("FilePathLink");


In this code, 'fs.unlinkSync()' is likely to run first, which would delete the test.txt file before it is read.

To avoid this, code can be written in a clear non-blocking way:

const fs = require("fs");
fs.readFile("FilePathLink", (readFileErr, data) => {
	if (readFileErr) throw readFileErr;
	console.log(data);
	fs.unlink("FilePathLink", (unlinkErr) => {
		if (unlinkErr) throw unlinkErr;
	});
});


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

Read about, Difference Between Analog and Digital Computer

Frequently Asked Questions

Is Node JS frontend or backend?

Node.js makes it simpler for developers to do their jobs because it can be used in both the frontend and backend of programs and websites.

What is a callback in node.js?

A callback is a function called after completing a function. It is used to prevent blocking.

What makes asynchronous and non-blocking in node.js different?

Asynchronous improves 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. 

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

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

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

The event loop and callback mechanism move I/O operations from the JavaScript thread to the 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.

Conclusion

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.


You may refer to our Guided Path on Code Studios for enhancing your skill set on DSACompetitive ProgrammingSystem Design, etc. Check out essential interview questions, practice our available mock tests, look at the interview bundle for interview preparations, and so much more!

Happy Learning, Ninjas!

Previous article
Node.js file stats and paths
Next article
How to use Class in Node.js
Live masterclass