Error-First Callback in Node.js
Last Updated :
16 Feb, 2022
Error-First Callback in Node.js is a function which either returns an error object or any successful data returned by the function.
- 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.
- 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:
Javascript
const fs = require( "fs" );
const file = "file.txt" ;
const ErrorFirstCallback = (err, data) => {
if (err) {
return console.log(err);
}
console.log( "Function successfully executed" );
};
fs.readFile(file, ErrorFirstCallback);
|
Output:
Example 2:
Javascript
const fs = require( "fs" );
const file = "file.txt" ;
const ErrorFirstCallback = (err, data) => {
if (err) {
return console.log(err);
}
console.log( "Function successfully executed" );
console.log(data.toString());
};
fs.readFile(file, ErrorFirstCallback);
|
Output:
Share your thoughts in the comments
Please Login to comment...