Open In App

What is an error-first callback in Node.js ?

Last Updated : 07 Mar, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we are going to explore the Error-first callback in Node.js and its uses. Error-first callback in Node.js is a function that returns an error object whenever any successful data is returned by the function.

The first argument is reserved for the error object by the function. This error object is returned by the first argument whenever any error occurs during the execution of the function.

The second argument is reserved for any type of successful data returned by the function. The error object is set to null when no error occurs.

The below example and steps show the implementation of the Error-first callback:

Step 1: Create a file with the name index.js.

Step 2: Add the fs module import in this module

Step 3: Once the module is imported, we will be implementing the error-first callback function on this method using the fs module. The fs module can be used through the following statement in index.js

const fs = require("fs");

Use the following command to execute the index.js file.

node index.js

In the below example, we will be using the fs.readFile() method for showing the use of the error-first callback function.

Example 1: 

Javascript




// Using the fs module through import
const fs = require("fs");
  
// The following file does not exists
const file = "file.txt";
  
// This should throw an error
// using the Error-first callback
const ErrorFirstCallback = (err, data) => {
if (err) {
    return console.log("Error: " + err);
}
console.log("Function successfully executed");
};
  
// Executing the function
fs.readFile(file, ErrorFirstCallback);


Output:

output.png

Example 2:

Javascript




// Using the fs module through import
const fs = require("fs");
  
// This file exists in the system
const file = "file.txt";
  
// Calling the function to read file
// with error callback and data
const ErrorFirstCallback = (err, data) => {
if (err) {
    return console.log(err);
}
console.log("Function successfully executed");
console.log("File Content : " + data.toString());
};
  
// Executing the function
fs.readFile(file, ErrorFirstCallback);


Output:



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads