I try to calculate the size of all files in a given directory plus in all sub directories. This is what I have so far:
const fs = require('fs');
if (process.argv.length < 3) {
console.log("no argument given");
process.exit(-1);
}
const dir = process.argv[2];
let bytes = 0;
(getSize = async dir => {
fs.readdir (dir, (err, list) => {
list.forEach (file => {
fs.stat (dir + file, (err, stat) => {
if (stat.isDirectory()) {
getSize(dir + file + "/");
} else {
console.log(file + " [" + stat.size + "]");
bytes += stat.size;
}
});
});
});
})(dir);
setTimeout(() => {
console.log(bytes + " bytes");
console.log(bytes / 1000 + " Kbytes");
}, 500);
Is there a way to avoid the timeout in the end to wait for the result? I heard it is possible with async/await but I don't know how. I also want to keep this general asynchron approach if possible.
fs.readdiris not based on promises, so evenasync dirmakes no sense here.. You might want to look into using something to promisify the nodejs fs functions, You might find this useful -> github.com/normalize/mz