Node.js | Callback Concept

A callback is a function which is called when a task is completed, thus helps in preventing any kind of blocking and a callback function allows other code to run in the meantime. Callback is called when task get completed and is asynchronous equivalent for a function. Using Callback concept, Node.js can process a large number of requests without waiting for any function to return the result which makes Node.js highly scalable. For example: In Node.js, when a function start reading file, it returns the control to execution environment immediately so that the next instruction can be executed. Once file I/O gets completed, callback function will get called to avoid blocking or wait for File I/O.

Example 1: Code for reading a file synchronously (blocking code) in Node.js. Create a text file inputfile1.txt with the following content:

Hello Programmer!!!
Learn NodeJS with GeeksforGeeks

Create a sync.js file with the following code:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Write JavaScript code
var fs = require("fs");
var filedata = fs.readFileSync('inputfile1.txt');
console.log(filedata.toString());
console.log("End of Program execution");

chevron_right


Explanation: fs library is loaded to handle file-system related operations. The readFileSync() function is synchronous and blocks execution until finished. The function blocks the program until it reads the file and then only it proceeds to end the program
Output:

Example 2: Code for reading a file asynchronously (non-blocking code) in Node.js. Create a text file inputfile1.txt with the following content.

Hello Programmer!!!
Learn NodeJS with GeeksforGeeks

Create a async.js file with the following code:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Write a JavaScript code
var fs = require("fs");  
    
fs.readFile('inputfile1.txt', function (ferr, filedata) {  
    if (ferr) return console.error(ferr);  
    console.log(filedata.toString());  
}); 
console.log("End of Program execution");  

chevron_right


Explanation: fs library is loaded to handle file-system related operations. The readFile() function is asynchronous and control return immediately to the next instruction in the program while the function keep running in the background. A callback function is passed which gets called when the task running in the background are finished.
Output:

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

1


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.