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...
Or else is there any universal way to get size of the directory in all three platforms and all machines.
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);
}
})();