0

I want to check if a file exists with nodejs from Electron. But I can't return a boolean value such as "true" or "false". The callback function doesn't return anything. Apparently the callback function executes after the main function. I tried many methods and nothing happens.

function fileExists(filename){
    var result;
    fs.stat(filename, function(err, stat) {
        if(err === null) {
            result = true;
        } else if(err.code == 'ENOENT') {
            result = false;
        }
    });
    return result;
}

//usage
if(fileExists('myFile.txt') === true){
    //proceed
}else{
    //error
}
  • Look at the answers on the linked question. `stat` call is async, the callback will be executed after the call completes but `result`-undefined will be returned before it. – Tushar Mar 28 '17 at 15:18
  • Yes, but in the question that you send me they use an `alert()` as return. This is the same problem. Check my function, this is the purpose usage: `if(fileExists(myFile.txt) === true){ //do something }` – Nataniel López Mar 28 '17 at 16:25
  • Have a look at http://stackoverflow.com/q/23667086/218196 and http://stackoverflow.com/q/14220321/218196 . You have to restructure your code. Or use the sync version of `stat`. However, you cannot magically make an async function sync. – Felix Kling Mar 28 '17 at 16:31
  • Thanks, I changed the function to `fs.existsSync();` I not used it first because in some pages said that was deprecated but the deprecated function is `fs.exists();` – Nataniel López Mar 28 '17 at 16:37

0 Answers0