I am new to node.js, I am trying to corelate these two features of node.js,
node.js has two types api functions, i.e synchronous and asynchronous
node.js support non blocking I/O
Suppose api is making synchronous call, node.js feature non blocking I/O will not be used right?
Will synchronous and asynchronous modify node.js working internally, especially the feature non blocking I/O ?
const fs = require('fs');
// Asynchronous function
fs.readFile('data.json', 'utf8', function (err,data) {
if (err) {
return console.log(err);
}
console.log("Below is the Data from Asynchronous function call")
console.log(data);
});
// Synchronous function
var data = fs.readFileSync('data.json','utf8');
console.log("Below is the Data from Synchronous function call")
console.log(data);
In nodejs:
Asynchronous I/O == non-blocking I/O
Synchronous I/O == blocking I/O
While asynchronicity and blocking are technically not exactly the same thing, those two terms are often used interchangeably when talking about I/O operations within nodejs and that's probably because all asynchronous I/O operations in nodejs are also non-blocking and all synchronous I/O operations in nodejs are also blocking.
Will synchronous and asynchronous modify node.js working internally
Yes, they work differently internally.
For example, asynchronous file I/O operations use a thread pool and run the file operation in a separate OS thread, leaving the Javascript thread free to do other things (run other Javascript).
Synchronous file operations do not use the thread pool. They just call OS file operations directly which (by the design of the OS calls they use) will block the main thread until they complete.