Monday 8 October 2018

Node.js: Error-first callbacks

Error-First pattern is a standard callback pattern provided by node.js

How to define Error-First callback?
There are two rules while defining Error-First callback.

Rule 1: First argument of the callback function is reserved for an error object. Whenever any error occurs, the argument is populated with error information. If no error occurred, then er argument will be set to null

Rule 2: Second argument is reserved for any successful response data, any successful data will be returned in the second argument.

That’s it…let me explain with an example.

I am going to read a file using ‘readFile’ method of fs module. Signature of readFile method looks like below.

fs.readFile(path[, options], callback)
The callback is passed with two arguments (err, data), where
a.   err: Whenever any error occurs, the argument is populated with error information.
b.   Data: is the contents of the file.

input.txt
Two roads diverged in a yellow wood,
Jb_modern_frost_2_eAnd sorry I could not travel both
And be one traveler, long I stood
And looked down one as far as I could
To where it bent in the undergrowth;

HelloWorld.js
var fileSystem = require("fs");
var inputFile = 'input.txt';

fileSystem.readFile(inputFile, function(error, data) {
 if (error)
  return console.error(error);
 console.log(data.toString());
});




Previous                                                 Next                                                 Home

No comments:

Post a Comment