In this post, we will learn about Synchronous and Asynchronous behavior in Node.js.
Synchronous and Asynchronous behavior in Node.js
In the above code, we have used a synchronous task using readFileSync, which is used for reading a file. So when the file2.txt value is read, only after that line number 4 gets printed to the console. So, it is blocking the code.
Suppose you are reading a large file. It can take some time, so in this scenario, the next line code will not run until the file is read. So, synchronous tasks will block other lines of code.
To avoid this issue, we write asynchronous code which prevents code blocking. See the image attached below, which shows a non-blocking code.
In this, I used readFile for asynchronous task. Inside it, I have passed my file name, utf-8, and a callback function. In the next line, I wrote a random console.log() statement.
When I run this code, line number 5 gets printed first because it is an asynchronous code where the code will not be blocked. As soon as readFile gets the value of file2.txt, it will print that value in the console without blocking other code.
This is why line number 5 gets printed first because readFile takes some time to read this file and to get the data, and it’s an asynchronous code, so it is non-blocking therefore, the next line code gets executed.
As we know, node.js is single-threaded, and that is why we have to use so many callback functions in the node.