top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

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

+1 vote
463 views
What is an error-first callback in Node.js?
posted Jun 2, 2017 by Jdk

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes

Before discussing about Error-first callbacks, we should know what exactly is callback in Node.js. A callback is an asynchronous equivalent for a function which is being called when a given task is completed.

Node.js makes heavy use of callbacks, all the API's are written such as way that it supports callbacks. The advantage of using callback is that it makes Node.js highly scalable i.e. processing high number of request without waiting for any function to complete. A simple example of callback is as follows in which we are passing a function (callBackFunc) as an argument to another function.

var callBackFunc = function () {
  console.log('In am in callBackFunc');
};
callingFunction(argument, callBackFunc);

The "error-first" callback is nothing but a standard protocol for Node callbacks. The "error-first" callback has a simple rule that the first argument for the callback function should be an error object. If the error argument is null, then the operation was successful and if the error argument is not null, then an error has occurred.

Almost all Node.js code follows this style because without it developer has to spent a lot of time in maintaining different signature and styles for each and every callback.

Lets take an example of fs.readFile, in which the callback gets two arguments err and data.

fs.readFile('test.txt', function(err, data) {
  if(err) throw err;
  console.log(data); // data is the file content
});

As you can see in the above example the first argument of a callback function is Error object thus it is an "error-first" callback. If there is an error throw the error otherwise the reading operation is successful.

answer Jun 26, 2017 by Manikandan J
Similar Questions
0 votes

Am new to node.js.In every document i saw node js is nothing but non blocking and event driven.But am still unaware about what is non-blocking & event driven.Can any one please explain about this.

...