Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nodejs return console.log('...')?

Tags:

node.js

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?

like image 393
hwkd Avatar asked Oct 31 '25 16:10

hwkd


2 Answers

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. */
  }
});
like image 96
tier1 Avatar answered Nov 02 '25 23:11

tier1


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.

like image 40
DevAlien Avatar answered Nov 02 '25 23:11

DevAlien



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!