Reading Json file with RNFS on react native

风流意气都作罢 提交于 2019-12-11 04:24:52

问题


I'am trying to access the content of a JSON file i just wrote with RNFS. I tried different ways, import, json-loader etc without success.

I write the file like :

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

Then i proceed to try to read it

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

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

Sadly i only get a 'promise' but can't seem to access directly the data. I get this kind of result in console.

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

And i would like to access the date field, just like cFile.date

Any help welcome thanks you


回答1:


It is a Promise that you get from the readFile call. You need to invoke 'then' on it like so:

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



回答2:


try this:

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);


来源:https://stackoverflow.com/questions/49770756/reading-json-file-with-rnfs-on-react-native

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!