Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get totalsize of files in directory?

Tags:

node.js

How to get totalsize of files in directory ? Best way ?

like image 343
Bdfy Avatar asked Sep 23 '11 12:09

Bdfy


2 Answers

Here is a simple solution using the core Nodejs fs libraries combined with the async library. It is fully asynchronous and should work just like the 'du' command.

var fs = require('fs'),
    path = require('path'),
    async = require('async');

function readSizeRecursive(item, cb) {
  fs.lstat(item, function(err, stats) {
    if (!err && stats.isDirectory()) {
      var total = stats.size;

      fs.readdir(item, function(err, list) {
        if (err) return cb(err);

        async.forEach(
          list,
          function(diritem, callback) {
            readSizeRecursive(path.join(item, diritem), function(err, size) {
              total += size;
              callback(err);
            }); 
          },  
          function(err) {
            cb(err, total);
          }   
        );  
      }); 
    }   
    else {
      cb(err);
    }   
  }); 
}   
like image 117
loganfsmyth Avatar answered Oct 04 '22 00:10

loganfsmyth


I tested the following code and it works perfectly fine. Please do let me know if there is anything that you don't understand.

var util  = require('util'),
spawn = require('child_process').spawn,
size    = spawn('du', ['-sh', '/path/to/dir']);

size.stdout.on('data', function (data) {
  console.log('size: ' + data);
});


// --- Everything below is optional ---

size.stderr.on('data', function (data) {
  console.log('stderr: ' + data);
});

size.on('exit', function (code) {
  console.log('child process exited with code ' + code);
});

Courtesy Link

2nd method:

var util = require('util'), exec = require('child_process').exec, child;
child = exec('du -sh /path/to/dir', function(error, stdout, stderr){
    console.log('stderr: ' + stderr);
    if (error !== null){
        console.log('exec error: ' + error);
    }
});

You might want to refer the Node.js API for child_process

like image 32
MT. Avatar answered Oct 04 '22 01:10

MT.