Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RNFS.exists() always returns TRUE

I am using react-native-fs and for some reason whenever I use the exists() method it is always returning as TRUE. A sample of my code looks like this:

let path_name = RNFS.DocumentDirectoryPath + "/userdata/settings.json";

if (RNFS.exists(path_name)){
    console.log("FILE EXISTS")
    file = await RNFS.readFile(path_name)
    console.log(file)
    console.log("DONE")
}
else {
    console.log("FILE DOES NOT EXIST")
}

The output at the console is "FILE EXISTS", then an error is thrown that says:

Error: ENOENT: no such file or directory, open /data/data/com.test7/files/userdata/settings.json'

How can it exist using the exists method, but not the readFile method?

On further checking it seems that RNFS.exists() is always returning true, no matter what the filename is. Why is it always returning true?

A display of path_name says /data/data/com.test7/files/userdata/settings.json.

Even if I change my code to something nonsensical like the following code:

if (RNFS.exists("blah")){
    console.log("BLAH EXISTS");
} else {
    console.log("BLAH DOES NOT EXIST");
}

It still evaluates to true and displays the message:

BLAH EXISTS

I have displayed the contents of the directory and verified these files do not exist.

like image 381
kojow7 Avatar asked Dec 18 '17 16:12

kojow7


1 Answers

That's because RNFS.exists() returns a Promise. Put a Promise object in a test of if statement will always be true.

Do this instead:

if (await RNFS.exists("blah")){
    console.log("BLAH EXISTS");
} else {
    console.log("BLAH DOES NOT EXIST");
}

Or:

RNFS.exists("blah")
    .then( (exists) => {
        if (exists) {
            console.log("BLAH EXISTS");
        } else {
            console.log("BLAH DOES NOT EXIST");
        }
    });
like image 79
Val Avatar answered Oct 22 '22 21:10

Val