Callbacks concept in Node.js

Callback has the same asynchronous property for a function. A callback function is called when completing a specific task. All Node APIs are written in the way of callback functions.

What is callback?

Callback has the same asynchronous property for a function. A callback function is called when completing a specific task. All Node APIs are written in the way of callback functions.

For example, a function to read the file starts with reading the file and returns the control so that the environment that executes the next command can execute. When the file I / O (read / write) file is completed, it will call a callback function, with the contents of the file as a parameter. Therefore there will be no blocking or waiting when reading / writing File. It makes Node.js more efficient, like having a higher number of requests without waiting for the results to return.

For example Blocking Code

Create a text line with the name input.txt with the following content

 QTM la trang Web huong dan cac bai lap trinh hoan toan mien phi cho tat ca moi nguoi !!!!! 

Create a js file named main.js with the following content:

 var fs = require ( "fs" ); var data = fs . readFileSync ( 'input.txt' ); console . log ( data . toString ()); console . log ( "Ket process" ); 

Now run the following command to see the result:

 $ node main . js 

Result:

 QTM is a Web page that contains all the scripts 
Welcome to the world !!!!!!
Let's get married

For example, Non-Blocking Code

Create a file named input.txt with the following content:

 QTM la trang Web huong dan cac bai lap trinh hoan toan mien phi cho tat ca moi nguoi !!!!! 

Update main.js with the following code:

 var fs = require ( "fs" ); fs . readFile ( 'input.txt' , function ( err , data ) { if ( err ) return console . error ( err ); console . log ( data . toString ()); }); console . log ( "Ket process" ); 

Now run main.js to see the result:

 $ node main . js 

Result:

 Let's get married 
QTM is a Web page that contains all the scripts
Welcome to the world !!!!!!

These two examples explain the definition of blocking and non-blocking calls. The first example shows that the program locks until it reads the file and continues to run only a few seconds later, the second program does not wait for the file to read and continues to print "Ket" after the same time. show program.

According to Tutorialspoint

Previous article: NPM in Node.js

Next: Event Loop in Node.js

Update 25 May 2019
Category

System

Mac OS X

Hardware

Game

Tech info

Technology

Science

Life

Application

Electric

Program

Mobile