【问题标题】:RNFS.exists() always returns TRUERNFS.exists() 总是返回 TRUE
【发布时间】:2017-12-18 16:23:22
【问题描述】:

我正在使用 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”,然后抛出一个错误,上面写着:

错误:ENOENT:没有这样的文件或目录,打开 /data/data/com.test7/files/userdata/settings.json'

如何使用exists方法而不是readFile方法存在?

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

路径名显示为/data/data/com.test7/files/userdata/settings.json

即使我将代码更改为无意义的代码,例如以下代码:

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

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

BLAH EXISTS

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

【问题讨论】:

  • path_name 上尝试console.log,从错误日志中看起来不正确
  • @Val 有趣,上面写着/data/data/com.test7/files/userdata/settings.json。不知道为什么它有两次 /data 或者它是否应该是这样。
  • @Val 另外,我最初的错误消息中有undefined,尽管我认为这是由于我的测试用例中的 DocumentDirectoryPath 拼写错误造成的。现在已经解决了,我已经相应地调整了我的问题。

标签: react-native react-native-fs


【解决方案1】:

这是因为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");
        }
    });

【讨论】:

    猜你喜欢
    • 2013-08-06
    • 2017-05-10
    • 2013-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多