r1si
r1si

Reputation: 1164

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?

Upvotes: 2

Views: 7769

Answers (2)

Mtl Dev
Mtl Dev

Reputation: 1622

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;
  }
}

Upvotes: 8

r1si
r1si

Reputation: 1164

from the nodejs FS documentation:

fs.accessSync(path[, mode])#

Synchronous version of fs.access(). This throws if any accessibility checks fail, and does nothing otherwise.

the accessSync function don't have callback argument so you need to throws

here an example:

try{
   fs.accessSync("real_exixs_path", fs.R_OK | fs.W_OK)
}catch(e){
   //error
}
//success!

Upvotes: 2

Related Questions