在 React Native 上使用 RNFS 读取 Json 文件

IT技术 javascript json reactjs react-native fs
2021-05-26 15:39:57

我正在尝试访问我刚刚用 RNFS 编写的 JSON 文件的内容。我尝试了不同的方法,导入、json-loader 等,但没有成功。

我把文件写成:

    var obj = {
    date: moment().format(),
    counter: 0 };
    var json = JSON.stringify(obj);
    RNFS.writeFile(path, json, 'utf8')
    .then((success) => {
      count++;
      console.log('FILE WRITTEN! : ');
    })
    .catch((err) => {
        console.log(err.message);
    });

然后我继续尝试阅读它

var path = RNFS.DocumentDirectoryPath + '/test.json';

const cFile = RNFS.readFile(path, 'utf8');

可悲的是,我只得到一个“Promise”,但似乎无法直接访问数据。我在控制台中得到这种结果。

Promise {_40: 0, _65: 0, _55: null, _72: null}
_40:0
_55:"{"date":"2018-04-11T10:52:52+02:00","counter":0}"
_65:1
_72:null
__proto__:Object

我想访问日期字段,就像 cFile.date

欢迎任何帮助谢谢

2个回答

这是您从 readFile 调用中获得的 Promise。您需要像这样调用“then”:

RNFS.readFile(path, 'utf8')
    .then((contents) => {
    // log the file contents
    console.log(contents);
  })
  .catch((err) => {
    console.log(err.message, err.code);
  });

试试这个:

let asset_content = null;
try {
    await RNFetchBlob.fs.readFile(path, 'utf8')
      .then((data) => {
        asset_content = data;
        console.log("got data: ", data);
      })
      .catch((e) => {
        console.error("got error: ", e);
      })
  } catch (err) {
    console.log('ERROR:', err);
}
const assets = JSON.parse(asset_content);