Puka
Puka

Reputation: 1575

Javascript sum directory size inside a foreach

I'm having trouble with increasing a variable each time forEach is called.

The goal is to get the total size of a directory by summing the size of all the files inside it. The problem that I've got is to correctly understand where should I put the variables so that the correct size is computed.

Indeed, for the moment, the size calculated is the one of individual files instead of the total size. What am I missing ?

function walk(dir) {
  let
    n = 0,
    size = 0,
    totalSize = 0;

  function walk(dir) {

    fs.readdirSync(dir).forEach(file => {

      let fullPath = path.join(dir, file);


      totalSize += size; //Total size ; should it be here ?
      ++n;

      console.log(size);

      if (fs.lstatSync(fullPath).isDirectory()) {
        --n;
        walk(fullPath);
      } else {
        size = fs.statSync(fullPath).size; // Get size of file
        listFiles.write(size + "\n"); // Write file size into copyList.xml
      }

    });
  }
  return walk(dir);
}

Current output :

340747217
18607
283163346
25332
287107119
22240
281853153
219100996
204879388
210185951
26321
278784426
21899
22695
238503727
29866
266805926
21697
285134805

Upvotes: 0

Views: 945

Answers (2)

num8er
num8er

Reputation: 19372

No need to reinvent the wheel (:

There are tons of way to achieve that:

1) Calling command and getting output:

du -s YourPathHere | cut -f1

with JS:

const { exec } = require('child_process');
exec('du -s YourPathHere | cut -f1', (error, stdout, stderr) => {
  if (error) {
    throw error;
  }

  console.log(parseInt(stdout));
});    

2) Simply use get-folder-size module it's asynchronous out of box (does not use *Sync methods)

const {promisify} = require('util');
const getFolderSize = promisify(require('get-folder-size'));

(async () => {
  try {
    const size = await getFolderSize('/your-path');
  }
  catch(error) {
    console.error(error);
  }  
});

or callback way:

const getFolderSize = require('get-folder-size');

getFolderSize(myFolder, (error, size) => {
  if (error) { 
    throw error; 
  }

  console.log(size);
});

Upvotes: 1

Kavindra
Kavindra

Reputation: 1707

You are calculating the total size in a wrong place and also the way of calculation is wrong. size = + size does not add new size into the existing value. Use a new variable to accumulate total size.(totalSize)

function walk(dir) {
  let n = 0,
     size = 0;
     totalSize = 0;

  function walk(dir) {
      fs.readdirSync(dir).forEach(file => {
      let fullPath = path.join(dir, file);
      ++n;

      if (fs.lstatSync(fullPath).isDirectory()) {
          --n;
          walk(fullPath);
      } else {
          size = fs.statSync(fullPath).size; // Get size of file
          totalSize += size; // Calculate total size
          listFiles.write(size + "\n"); // Write file size into copyList.xml
      }
    });
  }
  return walk(dir);
}

Upvotes: 3

Related Questions