Node.js asynchronous vs. synchronous.

As the title says, in this blog I’m going to be talking about the differences between asynchronous and synchronous code in Node.js

So let’s start with asynchronous. As we know, Node is very fast and efficient. Node utilises a non-blocking I/O model that’s popular in industry, and used a lot in start ups, and big companies. Node.js is run on one single thread. Every user will be on the same thread when the app is running. When we have asynchronous code, it will not block the loading of other web page components. This will enhance the user experience and optimize bandwidth use, particularly for mobile users, who currently make up a large chunk of internet users. As I mentioned previously, Node.js is non-blocking, which ensures that several requests can be accepted at once. Almost all is done asynchronously in Node programming, but certain functions in the Node.js core have both synchronous and asynchronous variants. We should use the asynchronous functionality inmost cases to get the benefits of Node.js. Here is an instance of a asynchronous and synchronous model being compared using file_system.readFile:

Asynchronous way:

Result of the asynchronous model:

As we can tell, with the asynchronous way the system is prepared to perform another operation, and instead when the file is done reading, the callback function is called. See the output, run the last command first, and logs to the console “Read this file.”, then prints the contents of the file.

The synchronous way:

Result of synchronous model:

The code block looks simple, readFileSync() reads the whole file and stores it in the memory, then goes to the console to log the data and a message. This is the synchronous version and all is paused until the reading of the file is complete.

I hope this blog helps you understand asynchronous vs synchronous code in Node.js better!

Programmer