0

I'm trying to check with a function, if a file exists or not. For that, i'm using:

function checkDirectoryOrFile(pathToCheck) {
// Resolve the path
var sanitizedPath = path.resolve(pathToCheck);

var statusTest = null;

filesystem.access(sanitizedPath, filesystem.R_OK | filesystem.W_OK, function (error) {
    // Is null when everything is fine
    if(!error) {
        // Update the return status to true
        statusTest = true;
    }

    statusTest = false;
});

console.log(statusTest);

// Returns the status
return statusTest;
}

My problem is, that "statusTest" stays on "null" instead true or false. Any suggestions? I've tried to save the status in a superglobal, etc. but that won't help, to be honest..

Tyralcori
  • 1,079
  • 13
  • 33
  • 2
    Possible duplicate of [How to return value from an asynchronous callback function?](http://stackoverflow.com/questions/6847697/how-to-return-value-from-an-asynchronous-callback-function) – Mike Cluck Feb 02 '16 at 20:50
  • The reason I marked this as a duplicate of that other question is because `filesystem.access` is an asynchronous function. That's why the value of `statusTest` hasn't changed by the time you return from the function. – Mike Cluck Feb 02 '16 at 20:51
  • 1
    Also, your callback function will always set `statusTest = false`. Anyhow, use a callback function or use `accessSync` if you must. – Alexander O'Mara Feb 02 '16 at 20:54
  • @Alexander O'Mara no, if you invert `null` it became true. So it's true and can set the `statusTest` to `true` – Tyralcori Feb 02 '16 at 20:56
  • 1
    use the sync version or write async js – dandavis Feb 02 '16 at 20:56
  • 1
    Your `statusTest = false;` line runs unconditionally, after the conditional `statusTest = true;`. You're not inverting null in your sample code. – Alexander O'Mara Feb 02 '16 at 20:56

0 Answers0