等待所有流完成 - 流式传输文件目录

时间:2016-05-14 17:25:20

标签: node.js node-streams

我在client.upload中使用pkgcloud上传文件目录。所有流完成后执行回调的最佳方法是什么?是否有内置的方式来注册每个流" s"完成"事件并在他们全部被解雇后执行回调?

var filesToUpload = fs.readdirSync("./local_path"); // will make this async

for(let file of filesToUpload) {
    var writeStream = client.upload({
        container: "mycontainer,
        remote: file
    });
    // seems like i should register finish events with something
    writeStream.on("finish", registerThisWithSomething);
    fs.createReadStream("./local_path/" + file).pipe(writeStream);
}

2 个答案:

答案 0 :(得分:21)

执行此操作的一种方法是为每次上传生成Promise任务,然后使用Promise.all()

假设您使用的是ES6,代码看起来像这样:

show partitions status_logs

或者,如果您有权使用async / await,则可以使用此功能。例如:

const uploadTasks = filesToUpload.map((file) => new Promise((resolve, reject) => {
    var writeStream = client.upload({
        container: "mycontainer,
        remote: file
    });
    // seems like i should register finish events with something
    writeStream.on("finish", resolve);
    fs.createReadStream("./local_path/" + file).pipe(writeStream);
});

Promise.all(uploadTasks)
  .then(() => { console.log('All uploads completed.'); });

答案 1 :(得分:0)

查看NodeDir,其中包含readFilesStream / promiseFiles等方法。