React Native - Is there any way to find/search all images (.jpg/.png) from the external/internal storage?

Dha*_*ngh 5 javascript react-native

I am new to react-native development and using RNFetchBlob to work with files in internal storage, I wanted to create a gallery application and for that I need to fetch all the images present in the phone.

What i was able to do is fetch all files from a particular directory and search for images in it.

RNFetchBlob.fs.ls(RNFetchBlob.fs.dirs.DCIMDir).then((files) => {
        //Returns all files present in the directory
        console.log(files);
        //Returns files with .png or .jpg extension.            
        console.log(files.find((element) => {return element.match('/(.png)$|(.jpg)$|(.jpeg)$/g')}));

    }).catch((err) =>{
        console.log(err);
    });
Run Code Online (Sandbox Code Playgroud)

But with this approach I need to search in every directory by iterating into them with recursion, I wanted to know if there is some way fetching all the image files just with one command.

smi*_*mgr 0

我们可以有一个类似下面的递归函数。我认为一定有其他优化方法,但我最终这样做了。此外,如果lastModified没有改变,我们可以中断目录内的遍历。

async function findAllFilesByExtension(path = INTERNAL_STORAGE_PATH) {
   let files = [];
  const lsList = await RNFetchBlob.fs.lstat(path);

  if (!!lsList && Array.isArray(lsList)) {
    let dirs = [];

    lsList.forEach(item => {
      if (item.type === 'directory') {
        dirs.push(item);

        return;
      }
      if (item.type === 'file' && item.filename.match('/(.png)$|(.jpg)$|(.jpeg)$/g')) {
        files.push(item)

        return;
      }
    });

    const response = await Promise.all(unmodifiedDirs.map(item=>findAllFilesByExtension(item.path)));

    response.forEach(nestedFiles => {
      files = [...files, ...nestedFiles];
    });
  }

  return files;
}
Run Code Online (Sandbox Code Playgroud)