How to use Try/Catch to read files

Asked

Viewed 140 times

3

I have a method called readFileCredentials which aims to open a file and return the data that was inside that file, follows the code of that method:

readFileCredentials = function(file, cb){
    var _path = 'data-source/credentials/' + file;
    fs.readFile(_path, 'utf8', function(err, data){
        cb(err, data); 
    });
};

And to call this method, I built this code:

try{    
    readFileCredentials('arquivo.txt', function(err, data){
         console.log('Abriu');
    });
}catch(err){
    console.log('Não abriu');
}

The read is working, however, when I send a wrong file name, so there is an error, the catch is not triggered, what is wrong?

1 answer

5


The method fs.readFile already does it for you, to avoid generating errors that stop the code. Your idea is good, but it is not necessary. You can take a look at the source code of fs on Github.

What would be caught in the catch is passed to the variable err, so your logic should depend on that variable and not on a try/catch:

You can do it like this:

fs.readFile(_path, 'utf8', function(err, data){
    console.log(err ? 'Nao abriu' : 'Abriu');
    cb(err, data); 
});
  • 2

    I didn’t know this, it’s nice the JS do the right thing that is hard to find in other languages. Pity that the example of link gives a throw spoiling everything :D (of course there is situation that the throw may be suitable). Ah, it’s Node, so I didn’t know.

  • @bigown is the Node has taken some interesting steps for better compared to the native JS and the way to treat files.

  • I imagine, because the normal JS in browser has to be really limited :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.