Node JS: Synchronous and Asynchronous

Hello everyone, recently I am learning Node JS, and I found a very interesting topic, that's why I thought to share this with you all.

Node JS: Synchronous and Asynchronous

So there are many core modules in Node JS that we can use, but I was working on the "File-system" module that we can use to create files, write files, create directories, etc.

I found that there are two ways, either we can use the synchronous way or we can go for the asynchronous way.

In the synchronous method, as its name suggest that it will execute the task in a sequential method, suppose this is the JS code

1 .  console.log("Hello");
2 .  cosnole.log("World");

So first of all the first(1) line will be executed and then the second(2) line will be executed in synchronous method, right?

asynchronous

So in the same way, let's try to read a file and then print the data inside it and after that, we will display a message on the screen "operation completed"

As you can see first of all the content of file "note.txt" is displayed and then the message "Operation Completed" is displayed on the screen, right? Now let's try the same thing using the Asynchronous method.

fs.readFile("note.txt",'utf-8',
(err,data)=>{console.log(data);}
);
console.log("Operation Completed");

Now if I run this code, then first of all the content of file "note.txt" should be displayed then after the message "Operation completed" should be displayed on the screen, so let's check.

Wait ....what? first of all, the message has been displayed and after that content of file "note.txt" has been displayed.

The reason is both synchronous and asynchronous work in a very different way, so in the synchronous method, it will wait for the first task to get completed and then proceed to the next one, but in case of asynchronous, if the first task is taking some time to get completed so it will execute the other task in the queue and once the first task (file reading) is completed then it will display the data.

So this is the difference in working of synchronous and asynchronous methods.

NOTE: The awesome artwork used in this article was created by Chelsea Carlson.