How to create a new folder using react-native -fs

533 views Asked by At

How can I create a folder at the root of the internal storage in a React Native application, ensuring that the folder and its contents persist even if the app is uninstalled? I've explored the directory paths provided by react-native-fs, but none seem to fully meet my requirements. Ideally, I'd like to create a dedicated folder at the root level of the internal storage and save my files within it. Could anyone guide me on how to achieve this effectively?

1

There are 1 answers

14
Zeeshan Anwar On

Google Play Console policies restrict access to the root of internal storage, and apps are encouraged to use other storage solutions like the app-specific directory provided by getFilesDir() method.

If you want to create a directory in the internal storage that persists across app installs and uninstalls, you can only use the app-specific directories provided by the Android system. Here's how you can do it in React Native:

import { Platform } from 'react-native';
import RNFS from 'react-native-fs';

const folderName = 'myPersistedFolder';

async function createPersistedFolder() {
  try {
    const filesDir = Platform.OS === 'android' ? RNFS. DownloadDirectoryPath : RNFS.DocumentDirectoryPath;
    const folderPath = `${filesDir}/${folderName}`;

    const folderExists = await RNFS.exists(folderPath);
    if (!folderExists) {
      RNFS.mkdir(folderPath)
            .then(() => {
              console.log('Folder created successfully');
            })
            .catch(error => {
              console.error('Error creating folder:', error);
            });
      console.log('Persisted folder created:', folderPath);
    } else {
      console.log('Persisted folder already exists:', folderPath);
    }
  } catch (error) {
    console.error('Error creating persisted folder:', error);
  }
}

createPersistedFolder();