Folder Size - File System

Asked

Viewed 76 times

1

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

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

But you’re always calling me back null, 0 and not the actual size of the folder, I forgot something?

1 answer

0


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

But somehow it stays here, the idea is to go read a board and at each entry of this board add up the size of this entry. If the input is a directory, run the same code recursively.

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 file name with the script above):

node getSize.js ./lib

Browser other questions tagged

You are not signed in. Login or sign up in order to post.