Search code examples
react-nativereact-native-fs

How to access files and folders using react-native-fs library


I am using react-native-fs for file system access. However am unable to access files in ios.

Below is the code:

RNFS.readDir(RNFS.MainBundlePath)
.then((result) => {
    console.log('Got result', result);
    return Promise.all([RNFS.stat(result[0].path), result[0].path]);
})
    .then((statResult) => {
        console.log('stat result',statResult);
        if(statResult[0].isFile()){
            return RNFS.readFile(statResult[1], 'utf8');
        }
        return 'no file';
    })
        .then((contents) => {
            console.log('Got Contents',contents);
        })
.catch((err) => {
    console.log(err.message, err.code);
})

I am getting path files for MainBundlePath but not any other files/folders which are locally stored.


Solution

  • Answering my own question. I was finally able to access any files stored on android in react native using react-native-fs library.

    Tried ExternalStorageDirectoryPath as in the list of given constants.

    So below is the code (Provided by react-native-fs git repo):

    RNFS.readDir(RNFS.ExternalStorageDirectoryPath)
    .then((result) => {
    console.log('GOT RESULT', result);
    return Promise.all([RNFS.stat(result[0].path), result[0].path]);
    })
    .then((statResult) => {
    if (statResult[0].isFile()) {
    return RNFS.readFile(statResult[1], 'utf8');
    }
    return 'no file';
    })
    .then((contents) => {
    console.log(contents);
    })
    .catch((err) => {
    console.log(err.message, err.code);
    });