all files / file-manager-js/lib/ dirSize.js

100% Statements 25/25
100% Branches 4/4
100% Functions 0/0
100% Lines 21/21
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35                            
const list = require('./list');
const stat = require('./stat');
 
// calculates the size of all files in a dir tree
const dirSize = (fsReaddir, fsStat, join) => {
  const listFn = list(fsReaddir, fsStat, join);
  const statFn = stat(fsStat);
 
  return (path) => {
    let size = 0;
    const dirSizeFn = p => listFn(p)
      .then((entries) => {
        const { files } = entries;
        const { dirs } = entries;
        if (files.length > 0) {
          const sizes = files.map(f => statFn(f).then((stats) => {
            size += stats.size;
          }));
          return Promise.all(sizes).then(() => dirs);
        }
        return dirs;
      })
      .then((dirs) => {
        if (dirs.length > 0) {
          const sizes = dirs.map(dirSizeFn);
          return Promise.all(sizes).then(() => size);
        }
        return size;
      });
    return dirSizeFn(path);
  };
};
 
module.exports = dirSize;