Skip to content
Related Articles

Related Articles

Node.js | Callback Concept
  • Difficulty Level : Easy
  • Last Updated : 04 Dec, 2019

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:




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


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:




// 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");  


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
Recommended Articles
Page :