gpt4 book ai didi

react-native - RNFS.exists() 总是返回 TRUE

转载 作者:行者123 更新时间:2023-12-04 03:58:59 60 4
gpt4 key购买 nike

我正在使用 react-native-fs,出于某种原因,每当我使用 exists() 方法时,它总是返回 TRUE。我的代码示例如下所示:

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")
}

控制台的输出是“FILE EXISTS”,然后抛出一个错误说:

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



怎么可能存在使用 exists方法,但不是 readFile方法?

进一步检查似乎 RNFS.exists() 总是返回 true,无论文件名是什么。为什么它总是返回true?

path_name 的显示表示 /data/data/com.test7/files/userdata/settings.json .

即使我将代码更改为类似以下代码的无意义内容:

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

它仍然评估为 true 并显示消息:

BLAH EXISTS

我已经显示了目录的内容并验证了这些文件不存在。

最佳答案

那是因为 RNFS.exists() 返回 Promise .放一个 Promise if statement 测试中的对象永远是真的。

改为这样做:

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

要么:

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

关于react-native - RNFS.exists() 总是返回 TRUE,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47872464/

60 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com