1.

What are the API functions available in Node.js?

Answer»

There are two types of API functions available in Node.js:

1.Synchronous or BLOCKING functions where all other code execution is blocked till an I/O event that is being waited on completes. These are executed synchronously one after the other.

For eg: 

Reading a file called ‘file.txt’

const fs = require('fs'); const data = fs.readFileSync('file.txt’); // blocks here until file is read

Here the execution of further lines in the program will be blocked. If any error is thrown it needs to be caught immediately to avoid the crashing of the program.readFileSync() completely reads the CONTENT to the memory and then prints the data in the console. The blocking function has an adverse effect on the APPLICATION’s performance.

2.Asynchronous or Non-blocking functions are another type of API functions where multiple I/O calls can be performed without the execution of the program being blocked.

For eg: 

Reading a file “file.txt”

const fs = require('fs'); fs.readFile('file.txt’, function(err, data) => {   if (err) throw err;  });

Here reading of the file (readFile()) doesn’t block further execution of the next instruction in the program. The above function takes the file name and passes the data of the file as a reference to the callback handler. Then the file system object remains ready to take up any other file system operation. Asynchronous API functions increase the throughput by INCREASING the number of instructions handled per cycle time.



Discussion

No Comment Found