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?

1 Answer 1

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);
  });
Sign up to request clarification or add additional context in comments.

2 Comments

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
Brother, you can check this answer as well to find your file.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.