Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

node js FS accessSync set global variable path fail

I have a problem with Sync function in FS core of nodejs. for example I have a nodejs file with this syntax

var y;
fs.accessSync("real_exixs_path", fs.R_OK | fs.W_OK, function(err) {
  if (err) {
    console.log("File error!");
  } else {
    y = "foo";
  }
});

after running this code the global "y" variable still remain undefined and it won't set to "foo". Can someone help me?

like image 290
r1si Avatar asked Jul 19 '26 10:07

r1si


1 Answers

The accepted answer has an error, it will always run "success" whether a file exists or not.

Corrected version:

try{
   require('fs').accessSync("filename.ext", fs.R_OK | fs.W_OK)
   //code to action if file exists

}catch(e){
   //code to action if file does not exist
}

or, wrap it in a function:

function fileExists(filename){
  try{
    require('fs').accessSync(filename)
    return true;
  }catch(e){
    return false;
  }
}
like image 122
Mtl Dev Avatar answered Jul 20 '26 23:07

Mtl Dev



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!