I was looking at how to write files in node, and I found this block of code:
var fs = require('fs');
fs.writeFile("/tmp/test", "Hey there!", function(err) {
if(err) {
return console.log(err);
}
console.log("The file was saved!");
});
Now, inside the if(err){} block, where is this console.log(err) being returned to? How does the error handling work in node?
It is essentially doing nothing but breaking the logic chain of the callback.
Error handing in node is mainly callback based like you see here.
For example:
var fs = require('fs');
fs.writeFile("/tmp/test", "Hey there!", function(err) {
if (err) {
/* Handle error appropriately */
} else {
/* Code that relies on /tmp/test to exist. */
}
});
So basically, you are saying to fs.writeFile that when it is finished to call a function
function(err) {
if(err) {
return console.log(err);
}
console.log("The file was saved!");
}
Normally the callbacks do not care about what you return, So the return in case of error that you write there means that the code does not proceed, so that the second console.log is not printed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With