Reputation: 294
In node.js asynchronous functions have callback, however only some of them have err argument passed to that function. e.g. fs.writeFile has err as parameter
fs.writeFile('message.txt', 'Hello Node', function (err) {
if (err) throw err;
console.log('It\'s saved!');
});
but fs.watchfile doesn't
fs.watchFile('message.text', function (curr, prev) {
console.log('the current mtime is: ' + curr.mtime);
console.log('the previous mtime was: ' + prev.mtime);
});
First question is why some async functions have err argument in callback and some don't? How are we supposed to handle error of those which don't?
Also, as far as synchronous functions are concerned, are they all emitting "error" event which we can subscribe to and handle error this way?
var rs = fs.createReadStream("C:\\Temp\\movie.mp4");
rs.on('error', function(err) {
console.log('!error: ', err);
});
and last question: most of synchronous functions have Sync in name... why createReadStream does not?
Thanks!
Upvotes: 1
Views: 215
Reputation: 146114
First question is why some async functions have err argument in callback and some don't? How are we supposed to handle error of those which don't?
The vast majority of asynchronous functions in node code conform to the convention of the first argument to the callback function is the error. There are a very small number of exceptions, such as fs.exists, which is clearly documented as an antipattern that should not be used in the official docs.
In the case of watchFile
in particular, it's just the semantics of the API that it calls the callback repeatedly and only on success just because that's what it means to watch a file and in general the OSes don't provide a mechanism that has the semantic "notify me when anything goes wrong with this filesystem path", so there you have it.
Also, as far as synchronous functions are concerned, are they all emitting "error" event which we can subscribe to and handle error this way?
No. Your categorization of node mechanics is incomplete. There are at least 4 major paradigms:
JSON.parse
but not always. For example, parseInt
returns NaN
to indicate an error..then
. most of synchronous functions have Sync in name... why createReadStream does not?
Because it's not really synchronous. It's event emitter based streaming. The actual createReadStream
will synchronously return you the stream object, but the I/O is asynchronous and events won't start to be emitted until the next tick at the earliest.
I highly recommend the article Error Handling in Node.js on the joyent blog for the current best practices described thoroughly.
Upvotes: 5