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?
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With