Published

- 2 min read

How to check file exist in react native using “FileSystem” API

img of How to check file exist in react native using “FileSystem” API

You can check if a file exists in React Native for Android or iOS without using the react-native-fs package by using the built-in FileSystem API provided by React Native. Here’s an example of how you can do this:

file-exist-react-native-FileSystem-API.js

   import { Platform, NativeModules } from 'react-native';

const { FileSystem } = NativeModules;

const path = `${FileSystem.documentDirectory}/myFile.txt`;

FileSystem.getInfo(path)
  .then(stats => {
    if (stats.exists) {
      console.log('File exists');
    } else {
      console.log('File does not exist');
    }
  })
  .catch(error => {
    console.log(error);
  });

In this example, we are using the FileSystem API provided by React Native to check if a file called myFile.txt exists in the device’s document directory. First, we get the path to the file using the FileSystem.documentDirectory property, which gives us the path to the device’s document directory. Then, we use the getInfo() method to get information about the file. The getInfo() method returns a promise that resolves to an object containing information about the file, including whether it exists or not. We can check the exists property of the returned object to determine whether the file exists.

Note that the FileSystem API is available by default in React Native, so you don’t need to install any additional packages. However, this API provides limited functionality compared to the react-native-fs package, so if you need to perform more advanced file operations, you may want to consider using the react-native-fs package instead.