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?

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
r1si
  • 1,136
  • 2
  • 19
  • 34
  • @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 Jan 11 '16 at 11:01
  • Why do you think so? – thefourtheye Jan 11 '16 at 11:02
  • 1
    @thefourtheye my question ask about the synchronization function (Sync function) not about Asynchronous. :) – r1si Jan 11 '16 at 11:10

2 Answers2

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;
  }
}
Mtl Dev
  • 1,604
  • 20
  • 29
  • Why is that? Because you used `require('fs')`, or something else? – LarsW Aug 20 '16 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 Aug 21 '16 at 03: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 Aug 21 '16 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 Oct 31 '16 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!
r1si
  • 1,136
  • 2
  • 19
  • 34