Explain Callback Function in NodeJS

    Jan 28, 2022       by Suraj Roy

In Node.js, a callback is a function that is passed as an argument to another function and is executed after the function it was passed to has completed its task. Callbacks are commonly used in Node.js to handle asynchronous operations, such as reading or writing files, making network requests, or interacting with a database.

A callback function in Node.js typically takes two arguments: an error object and a result object. The error object is used to indicate whether an error occurred during the execution of the function, while the result object contains the result of the operation.

For example, a function that reads a file from the file system might take a callback function as an argument that is executed once the file has been read. The callback function would receive an error object as the first argument if there was an error reading the file, and the contents of the file as the second argument if the read was successful. Have a look on the below code:

 

 
// Import fs module
const fs = require('fs');
 
// fs.readFile() method is used here to read the file content
fs.readFile('file.txt', 'utf8', function(err, data){      
    // Show the content of the file
    console.log(data);
});
 

 

In Node.js, callbacks are used extensively, especially in the Node.js API, which heavily rely on callbacks to handle the non-blocking nature of the runtime environment. This allows the event loop to continue processing other tasks while the callback is waiting for the response from an IO operation to return.

Callbacks are important in NodeJS and it's one of the core concept that one should understand when working with NodeJS.


WHAT'S NEW

Find other similar Articles here: