Search code examples
javascriptiosswiftreact-nativereact-native-fs

Why React Native RNFS's copyFile() cannot access to existing file on iOS?


I'm trying to access and copy a file from "/Documents" folder (on ios simulator) with RNFS but while .exists() can find the file, .copyFile() returns error as "The file 'temp.jpg' doesn't exists"

Why that can happen?

Here is my source file path (and also I can access it with image components):

Also adding "file://" to path doesn't work too.

/Users/myusername/Library/Developer/CoreSimulator/Devices/D305Z9A4-6C67-4DFE-A07D-1EF4D0302B87/data/Containers/Data/Application/B933EF45-391F-4882-986F-92B5430823D0/Documents/temp.jpg

Here is my code snippet, newlyCroppedImagePath is the path above. exists() returns correct result but .copyFile() returns "doesn't exists"

    RNFS.exists(newlyCroppedImagePath)
    .then((success) => {
        console.log('File Exists!'); // <--- here RNFS can read the file and returns this
    })
    .catch((err) => {
      console.log("Exists Error: " + err.message);
    });

    RNFS.copyFile(newlyCroppedImagePath, tmpFilePath)
    .then((success) => {
        console.log('file moved!');

    })
    .catch((err) => {
      console.log("Error: " + err.message); // <--- but copyFile returns "doesn't exists" error for temp.jpg
    });

Solution

  • Getting true on

    RNFS.exists(newlyCroppedImagePath).then((success) => {
        console.log('File Exists!'); // <--- here RNFS can read the file and returns this
    })
    

    doesn't mean that the file exists.

    Since the exists() returns a Promise, the if condition will always be true.

    Try the following

    RNFS.exists(filePath).then((status)=>{
    if(status){
        console.log('Yay! File exists')
    } else {
        console.log('File not exists')
    }
    })
    

    Also, please check the available files in the directory by using RNFS.readDir() to check whether your file has been presented or not.

    Refer https://github.com/itinance/react-native-fs#readdirdirpath-string-promisestring