react-nativereact-native-fs

How to get folder size and lenght in react native


How to get folder size and number of files in a folder? I try with react-native-fs readDir.

let pat2 = RNFS.DocumentDirectoryPath + '/myFolder'
RNFS.readDir(pat2)
.then((result) => {
     console.log(result.size)
})
.catch((err) => {
  console.log(err.message, err.code);
});

Solution

  • I don't know if you still need the answer. But readDir returns an array of ReadDirItem which represents an item in the folder. Then you can simply iterate over the items and add the sizes of the items. The number of items in the folder is just the length of the array.

    For the sum I used the reduce function of lodash (_.reduce()), but you could also use a simple for-loop.

    await RNFS.readDir(FOLDER_PATH).then((result: ReadDirItem[]) => {
    
          // number of files in a folder
          const numOfItems: number = result.length;
    
          // calculate sum of dirItem sizes
          const folderEntriesSizeInBytes: number = _.reduce(
            result,
            (sum: number, currentItem: ReadDirItem) => {
              return sum + Number(currentItem.size);
            },
            0
          );
    
          const megaBytes = String(folderEntriesSizeInBytes / 1000000);
        });
      }