3

i want to write to a JSON file so i used react-native-fs here is the code:

const add = (n, p, pr) => {
    var RNFS = require('react-native-fs');

    var filePath = RNFS.DocumentDirectoryPath + '/items.json';

    RNFS.writeFile(filePath, '{name:hello}', 'utf8')
      .then((success) => {
        console.log('SUCCESS');
      })
      .catch((err) => {
        console.log(err.message);
      });
  };

it log success but didn't update the file any ideas?

lcl code base
  • 101
  • 2
  • 9

1 Answers1

0

Your file is updating successfully and if you want to check it please run the following code after your file is written. You will see the file's path and data of your saved file.

// get a list of files and directories in the main bundle
RNFS.readDir(RNFS.DocumentDirectoryPath)
  .then((result) => {
    console.log('GOT RESULT', result);

    // stat the first file
    return Promise.all([RNFS.stat(result[0].path), result[0].path]);
  })
  .then((statResult) => {
    if (statResult[0].isFile()) {
      // if we have a file, read it
      return RNFS.readFile(statResult[1], 'utf8');
    }

    return 'no file';
  })
  .then((contents) => {
    // log the file contents
    console.log("contents");
    console.log(contents); // You will see the updated content here which is "{name:hello}"
  })
  .catch((err) => {
    console.log(err.message, err.code);
  });
Shahnawaz Hossan
  • 2,695
  • 2
  • 13
  • 24
  • it work i can see the content i wrote to the file, but cant find the file anywhere this is what it log `[{"ctime": null, "isDirectory": [Function isDirectory], "isFile": [Function isFile], "mtime": 2020-06-19T19:07:30.000Z, "name": "items.json", "path": "/data/data/com.shoppinglist/files/items.json", "size": 12}, {"ctime": null, "isDirectory": [Function isDirectory], "isFile": [Function isFile], "mtime": 2020-06-19T19:00:30.000Z, "name": "ReactNativeDevBundle.js", "path": "/data/data/com.shoppinglist/files/ReactNativeDevBundle.js", "size": 5831985}]` the path does not exits on my pc – lcl code base Jun 19 '20 at 19:19
  • 1
    Brother, you can check [this answer](https://stackoverflow.com/questions/54840085/saving-a-files-in-react-native-using-reart-native-fs) as well to find your file. – Shahnawaz Hossan Jun 20 '20 at 16:39