Skip to content
Advertisement

Saving a files in React-Native using react-native-fs library

After saving a file using react-native-fs where does that file go?

It’s not explained in the documentation or I couldn’t find and it’s hard to figure.

Advertisement

Answer

When you create a file you have to specify a directory where to store the file. In the example below the path variable shows where the file will be written to.

var RNFS = require('react-native-fs');

// create a path you want to write to
// :warning: on iOS, you cannot write into `RNFS.MainBundlePath`,
// but `RNFS.DocumentDirectoryPath` exists on both platforms and is writable
var path = RNFS.DocumentDirectoryPath + '/test.txt';

// write the file
RNFS.writeFile(path, 'Lorem ipsum dolor sit amet', 'utf8')
  .then((success) => {
    console.log('FILE WRITTEN!');
  })
  .catch((err) => {
    console.log(err.message);
  });

There are several places you can store your files

The following directories are available:

  • MainBundlePath (String) The absolute path to the main bundle directory (not available on Android)
  • CachesDirectoryPath (String) The absolute path to the caches directory
  • ExternalCachesDirectoryPath (String) The absolute path to the external caches directory (android only)
  • DocumentDirectoryPath (String) The absolute path to the document directory
  • TemporaryDirectoryPath (String) The absolute path to the temporary directory (falls back to Caching-Directory on Android)
  • LibraryDirectoryPath (String) The absolute path to the NSLibraryDirectory (iOS only)
  • ExternalDirectoryPath (String) The absolute path to the external files, shared directory (android only)
  • ExternalStorageDirectoryPath (String) The absolute path to the external storage, shared directory (android only)

So all you have to do is choose the directory. Note these directories are on the device.

Seeing the files on the device

iOS Simulator

If you want to find the file on your simulator on iOS all you need to do is console.log the path, which should look something like this

/Users/work/Library/Developer/CoreSimulator/Devices/2F8BEC88-BF42-4D6B-81D4-A77E6ED8CB00/data/Containers/Data/Application/BC16D2A6-55A2-475C-8173-B650A4E40CF1/Documents/

Open Finder, select Go to folder

enter image description here

And then paste in the path and that will open the folder where the file is.

enter image description here

Android Emulator

If you console.log the path for the file you should get something like this

/data/user/0/com.awesomeapp/files/

You have to run the app from Android Studio, then you need to access the Device View Explorer. You do that by going to View -> Tool Windows -> Device File Explorer

enter image description here

That should then open a windows that looks like this, where you can then browse to the file path that you were given above.

enter image description here

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement