Synchronous vs Asynchronous in Node.js
This article shows the difference between synchronous and asynchronous in Node.js
Synchronous code also called blocking halts the program until the operation is complete. Asynchronous code also called non-blocking continues executing the program and doesn't wait for the operation to be complete. Most functions in the Node.js modules are asynchronous in nature that is to say they are asynchronous by default.
Let's read files using the file system module for Node.js in both synchronous and asynchronous versions to compare and know the differences.
Using fs.readFileSync() method to read the file sychronously.
const fs = require('fs');
const data = fs.readFileSync('file.txt', 'utf8');
console.log(data);
moreTasks();
In the above example, the readFileSync method reads the contents of the file first before it prints the data out. So this means without reading the content fully, the method won't go for the next line. Here console.log() will be called first before moreTasks().
Using fs.readFile() method to read the file asynchronously.
const fs = require('fs');
const http = require('http');
http.createServer((req, res) => {
fs.readFile('text.html', (err, data) => {
if (err) throw err;
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
res.end();
});
}).listen(4000);
moreTasks();
In the above example, moreTasks() will be called first because readFile is non-blocking as multiple requests can be handled at a time.
The benefit of asynchronous.
- Enhanced performance. Asynchronous code is preferred to synchronous because of better performance as it doesn't wait to execute the program. Synchronous serves one request at a time while asynchronous handle multiple requests at a time.
Conclusion.
Now you know that writing non-blocking code is necessary because it has a better performance. So as a developer, it is preferred to write asynchronous code because of the enhanced performance in the application. It is a better practice to use asynchronous code as a developer.
Until next time, stay tuned!!