top of page

Callback Functions in Node.js

Writer's picture: Anushka ShrivastavaAnushka Shrivastava

Updated: Oct 5, 2022


Node.js is an asynchronous platform. It does not wait for processes such as file i/o to finish. Instead, it uses callbacks.


A synchronous program in node.js would look like –



function processData () {
  var data = fetchData();
  data += 1;
  return data;
}
  

The above program fetches the data using function fetchData(). In the mean time, if it takes a long time in loading the data, the whole program gets blocked which causes system to sit still and wait. To prevent this issue from taking place, node.js uses callback functions.




CALLBACK FUNCTION


A callback is a function which is called at the completion of a given task, preventing any kind of blocking in the system work.


Using the concept of callback, node.js can process a large number of requests without waiting for other functions to return their respective results, making node.js highly scalable.


Now, let us try to understand callback with the help of an example code -


Let's create a text file named callback.txt, with content as -


Hello, this is a text file containing some words.


Now, we will try to read the above mentioned file using a callback function. The code goes like -



var fs = require("fs");     

fs.readFile('callback.txt', function (ferr, data) {  
    if (ferr) return console.error(ferr);  
    console.log(data.toString());  
});  
    
console.log("Execution ends");
    

The output produced will be -

Execution ends

Hello, this is a text file containing some words.



Working of the above code -

  • In the very first line of code, the fs library is included/loaded to handle file-related operations.

  • The readFile() function of fs module is an asynchronous function. So, control returns to the next instruction in the program, while the function keeps running in the background.

  • A callback function, here, function (ferr, data){ .... }, gets called when the task running in the background gets completed.


With this, we now know about callbacks, which are frequently used in node.js. All APIs in node.js are drafted in such a way that they support callbacks.


Thank you.



57 views0 comments

Recent Posts

See All

Hello World in Node.js

Node.js is an open source server environment that runs on various platforms such as Windows, Linux, Mac OS, etc. Node.js uses JavaScript...

תגובות


Graphic Cubes

Subscribe To Get Latest Updates

Subscribe to our newsletter • Don’t miss out!

Thanks for subscribing!

Blogger
bottom of page