Error-first callback in node.js

The “error-first” callback is nothing but a standard protocol for Node callbacks. Error-first callbacks are used to pass errors and data as well. The “error-first” callback has a simple rule that the first argument for the callback function should be an error object and it has to be checked to see if something went wrong. Additional arguments are used to pass data.

fs.readFile("./test.php", function(err, data) {  
  if (err) {
    // handle the error, the return is important here
    // so execution stops here
    return console.log(err)
  // use the data object

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

Share On Facebook
Share On Twitter
Share On Google Plus
Share On Linkedin
Share On Pinterest

Be the first to comment

Leave a Reply

Your email address will not be published.