How to use Try / Catch in reading files

3

I have a method called readFileCredentials that has the purpose of opening a file and returning the data that was inside that file, it follows the code of this 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've built this code:

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

The reading is working, however, when I send a wrong file name, so that there is an error, catch is not triggered, what's wrong?

    
asked by anonymous 05.05.2016 / 15:20

1 answer

5

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

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

You can do this for example:

fs.readFile(_path, 'utf8', function(err, data){
    console.log(err ? 'Nao abriu' : 'Abriu');
    cb(err, data); 
});
    
05.05.2016 / 15:23