2

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?

3
  • @thefourtheye this question isn't duplicate... I've found a solution... the Sync function don't have callback argument ! Synchronous version of fs.access(). This throws if any accessibility checks fail, and does nothing otherwise.
    – r1si
    Commented Jan 11, 2016 at 11:01
  • Why do you think so? Commented Jan 11, 2016 at 11:02
  • 1
    @thefourtheye my question ask about the synchronization function (Sync function) not about Asynchronous. :)
    – r1si
    Commented Jan 11, 2016 at 11:10

2 Answers 2

8

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;
  }
}
4
  • Why is that? Because you used require('fs'), or something else?
    – LarsW
    Commented Aug 20, 2016 at 16:53
  • Is your question regarding what is the error in the Accepted Answer? If so, the error is: the "//Success!" code is in the wrong place - it will always be run, whether the file exists or not. The correct behavior is "//Success!" should only be executed if the file actually exists... See my sample code above for an example.
    – Mtl Dev
    Commented Aug 21, 2016 at 3:06
  • Yes, of course. Stupid me. It seemed so obvious that I didn't even think of it, so I thought you meant something else (like fs.accessSync("real_exixs_path", fs.R_OK | fs.W_OK) always resulting in an error for some weird reason).
    – LarsW
    Commented Aug 21, 2016 at 11:44
  • @MtlDev thanks for this! The first example fails though as you reference the fs constants without setting the fs variable. In this instance you can probably just remove them.
    – roborourke
    Commented Oct 31, 2016 at 19:59
2

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!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.