Table of Contents
Callbacks Concept in Node.js is easier to understand when the core ideas are paired with practical examples. The sections below explain the topic clearly, highlight useful steps, and point out details that can prevent common errors.
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.
As an 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.
As an 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
As an 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 !!!!!!
Next: Event Loop in Node.js
FAQ
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.
What should you know about as an example, Blocking Code?
Create a text line with the name input.txt with the following content.
What should you know about as an example,, Non-Blocking Code?
Create a file named input.txt with the following content:
Reader Comments 0
Sign in with email or Google to join the discussion.