Open In App

Error-First Callback in Node.js

Error-First Callback in Node.js is a function which either returns an error object or any successful data returned by the function.

  1. The first argument in the function is reserved for the error object. If any error has occurred during the execution of the function, it will be returned by the first argument.
  2. The second argument of the callback function is reserved for any successful data returned by the function. If no error occurred then the error object will be set to null.

Below is the implementation of Error-First Callback:



Create a file with the name index.js. The file requires an fs module. We will be implementing an error-first callback function on methods of the fs module. fs module can be used in the program by using the below command:

const fs = require("fs");

The file can be executed by using the below command:



node index.js

We will be using fs.readFile()  to show error-first callback function. 

Example 1:




const fs = require("fs");
 
// This file does not exists
const file = "file.txt";
 
// Error first callback
// function with two
// arguments error and data
const ErrorFirstCallback = (err, data) => {
  if (err) {
    return console.log(err);
  }
  console.log("Function successfully executed");
};
 
// function execution
// This will return
// error because file do
// not exist
fs.readFile(file, ErrorFirstCallback);

Output:

Example 2:




const fs = require("fs");
 
// This file exists
const file = "file.txt";
 
// Error first callback
// function with two
// arguments error and data
const ErrorFirstCallback = (err, data) => {
  if (err) {
    return console.log(err);
  }
  console.log("Function successfully executed");
  console.log(data.toString());
};
 
// function execution
// This will return
// data object
fs.readFile(file, ErrorFirstCallback);

Output:


Article Tags :