Ram
Ram

Reputation: 432

Get size of folder using du command

I used to get size of directory using this code in my electron app

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);
});

It works in my machine. when i take build and run in another windows machine it throws du is not recognized as internal command like that...

  1. Why this works in my machine only not other windows machines.
  2. And also i doubt that it works in linux / mac machines ???
  3. how this du command works ??

Or else is there any universal way to get size of the directory in all three platforms and all machines.

Upvotes: 1

Views: 1936

Answers (5)

LT-Sites
LT-Sites

Reputation: 415

I know that this question is somewhat old, but recently I found myself looking for a clear and short answer on how to do it, if it is useful to someone, well, and if it has not only consumed a few bytes.

I must clarify that I do not I am an expert in anything, but I like to learn and this is what I learned looking for a solution to this:

*/
First declare the needs of a Child Process and [execSync()][1]
"the method will not return until the child process has fully closed"
*/

This script is a Synchronous operation

//Declares the required module
const execSync = require('child_process').execSync;
//Declare the directory or file path
const target = "Absolute path to dir or file";
/*
Declare a variable or constant to store the data returned,
parse data to Number and multiplying by 1024 to get total 
bytes
*/
const size = parseInt(execSync(`du '${target}'`)) * 1024;
//Finally return or send to console, the variable or constant used for store data
return size;

With exec or execSync can execute files, or commands, in Unix system when executes du 'some path' in a terminal, gets the disk utilization of the file or directory, and the absolute pat again,therefore it is necessary to make a parse to integer of the result, the execSync gets a buffer as result.

I use a Template String as parameter to avoid writing more lines of code since you don't have to deal with whitespace issues in the string path, this method supports these whitespace.

//If executed in a terminal
du 'path to file or directory including white spaces in names'
// returns something like
125485 path to file or directory including white spaces in names

All about du command for Unix

I don't speak English natively so I use a translator as an interpreter, my apologies for language errors.

All about du equivalent for Windows

Upvotes: 0

airos
airos

Reputation: 752

du is a Linux command. It is not usually available in Windows (no idea about Mac, sorry)

The child_process module provides the ability to spawn child processes. It seems you are just executing the command in the operating system. So, for getting a solution working on multiple systems, you could have two options:

  • Checking the operating system, and executing (with spawn) the appropriate system command, as you are doing now. This keeps the code simplest
  • Alternatively, using JavaScript code (there are a number of questions in StackOverflow about how to get directory size in node.js). I think this would be the safest way for covering any operating system without worries about commands support.

You must have installed some linux tools in your Windows system, but you cannot rely on having them available in any common Windows

Upvotes: 1

Cody Geisler
Cody Geisler

Reputation: 8617

You can use the built in node.js fs package's stat command... but oh boy will this blow up in memory if you do an entire drive. Best to probably stick to tools outside of node that are proven.

https://repl.it/@CodyGeisler/GetDirectorySizeV2

const { promisify } = require('util');
const watch = fs.watch;
const readdir = promisify(fs.readdir);
const stat = promisify(fs.stat);
const path = require('path');
const { resolve } = require('path');


const getDirectorySize = async function(dir) {
  try{
    const subdirs = (await readdir(dir));
    const files = await Promise.all(subdirs.map(async (subdir) => {
      const res = resolve(dir, subdir);
      const s = (await stat(res));
      return s.isDirectory() ? getDirectorySize(res) : (s.size);
    }));
    return files.reduce((a, f) => a+f, 0);
  }catch(e){
    console.debug('Failed to get file or directory.');
    console.debug(JSON.stringify(e.stack, null, 2));
    return 0;
  }
};

(async function main(){
  try{
    // Be careful if directory is large or size exceeds JavaScript `Number` type
    let size = await getDirectorySize("./testfolder/")
    console.log('size (bytes)',size);
  }catch(e){
    console.log('err',e);
  }
})();

Upvotes: 1

Yaroslav Gaponov
Yaroslav Gaponov

Reputation: 2099

Very primitive and sync code. For product you must switch to async functions.

const path = require('path');
const fs = require('fs');

function dirsizeSync(dirname) {
    console.log(dirname);
    let size = 0;
    try {
        fs.readdirSync(dirname)
            .map(e => path.join(dirname, e))
            .map(e => {
                try {
                    return {
                        dirname: e,
                        stat: fs.statSync(e)
                    };
                } catch (ex) {
                    return null;
                }
            })
            .forEach(e => {
                if (e) {
                    if (e.stat.isDirectory()) {
                        size += dirsizeSync(e.dirname);
                    } else if (e.stat.isFile()) {
                        size += e.stat.size;
                    }
                }
            });
    } catch (ex) {}
    return size;
}

console.log(dirsizeSync('/tmp') + ' bytes');

Upvotes: 1

andreybleme
andreybleme

Reputation: 689

1. The windows installed in your machine may have the sysinternals du command. It is not present in all windows installations. You may prefer to use windirstat.info or something more native like www.getfoldersize.com.

2. Since du a UNIX and Linux command for estimating file space usage, it should work in any UNIX like OS.

3. The du command is a command line utility for reporting file system disk space usage. It can be used to find out disk usage for files and folders and to show what is taking up space. It supports showing just directories or all files, showing a grand total, outputting in human readable format and can be combined with other UNIX tools to output a sorted list of the largest files of folders on a system. See: https://shapeshed.com/unix-du/

If you need it to work on UNIX and non-UNIX OS, you should first check what OS is been used by the user of your program an then execute a different command depending on the operation system that it is running on.

Upvotes: 2

Related Questions