简体   繁体   English

在node.js中使用async / await处理递归的结果

[英]Handle result of recursion with async/await in node.js

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? 有没有一种方法可以避免最终等待结果timeout I heard it is possible with async / await but I don't know how. 我听说有可能与async / await但我不知道如何。 I also want to keep this general asynchron approach if possible. 如果可能,我还希望保留这种一般的异步方法。

Promises are a bit easier to deal with. 承诺要容易一些。 Thankfully, node has a promisify function to convert those callback-based functions into Promise-returning functions. 值得庆幸的是,node具有一个promisify函数,可以将那些基于回调的函数转换为Promise返回函数。

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

async function getSize(dir) {
  const files = await readdir(dir);
  const sizes = await Promise.all(files.map(async file => {
    const stats = await stat(dir + file);
    return stats.isDirectory() ? getSize(dir + file + "/") : stats.size;
  }));
  return sizes.reduce((total, size) => total + size, 0);
}

const bytes = await getSize(process.argv[2]);
console.log(bytes + " bytes");
console.log(bytes / 1000 + " Kbytes");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM