Folder Size - File System

1

I'm trying to get the size of the folder that is in my project, the folder is called Testes , and in my file server.js I'm using the following method:

fs.stat('/Testes', function(err,stats){
    if(err) return console.log(err);
    console.log(null, stats.size); 
  })

But it's always returning me null, 0 and not the actual size of the folder, have I forgotten anything?

    
asked by anonymous 12.05.2017 / 15:00

1 answer

0

This in Node.js is not very simple. There are other platforms that are "more specialized" in the files part.

But the idea is to read a board and every entry in that board adds up to the size of that entry. If the entry is a directory, run the same code recursively.

It would look like this:

const fs = require('fs');
const path = require('path');
const folder = process.argv[2];

function getAllFiles(folder) {
  return new Promise((resolve, reject) => {
    fs.readdir(folder, (err, files) => {
      if (err) return reject(err);
      const filesWithPath = files.map(f => path.join(folder, f));
      Promise.all(filesWithPath.map(getFileSize)).then(sizes => {
        const sum = sizes.reduce(addValues, 0);
        resolve(sum);
      });
    });
  });
}

function getFileSize(file) {
  return new Promise((resolve, reject) => {
    fs.stat(file, (err, stat) => {
      if (err) return reject(err);
      if (stat.isDirectory()) getAllFiles(file).then(resolve);
      else resolve(stat.size);
    });
  });
}

function addValues(sum, val) {
  return sum + val;
}

function formatBytes(bytes) {
  if (bytes < 1024) return bytes + " Bytes";
  else if (bytes < 1048576) return (bytes / 1024).toFixed(3) + " Kb";
  else if (bytes < 1073741824) return (bytes / 1048576).toFixed(3) + " Mb";
  else return (bytes / 1073741824).toFixed(3) + " GB";
}

getAllFiles(folder)
  .then(sum => {
    console.log('O tamanho da diretoria "${folder}" é', formatBytes(sum));
  })
  .catch(e => console.log(e));

And to use you can do (assuming getSize.js is the filename with the above script):

node getSize.js ./lib
    
12.05.2017 / 16:01