【问题标题】:wait for all streams to finish - stream a directory of files等待所有流完成 - 流式传输文件目录
【发布时间】:2016-09-10 19:33:25
【问题描述】:

我在pkgcloud 中使用client.upload 来上传文件目录。在所有流完成后如何执行回调?是否有内置方法来注册每个流的“完成”事件并在它们全部触发后执行回调?

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

【问题讨论】:

  • 你可以使用 async.js 来解决这类问题。您可以使用 async.js 提供的方法作为async.waterfall()。一个函数的结果将作为回调参数传递给另一个函数。您应该查看它的文档。

标签: node.js node-streams


【解决方案1】:

一种方法是为每次上传生成一个Promise 任务,然后使用Promise.all()

假设您使用的是 ES6,那么代码将如下所示:

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

或者,如果您有权访问async / await - 您可以使用它。例如:

    const uploadFile = (file) => new Promise((resolve, reject) => {
      const writeStream = client.upload({
        container: "mycontainer",
        remote: file,
      });
      writeStream.on("finish", resolve);
      fs.createReadStream("./local_path/" + file).pipe(writeStream);
    }
    
    const uploadFiles = async (files) => {
      for(let file of files) {
        await uploadFile(file);
      }
    }

    await uploadFiles(filesToUpload);
    console.log('All uploads completed.');

【讨论】:

  • 对于那些感兴趣的人,我在处理hummus.js 中的流时遇到了一个稍微不同的问题,这个答案帮助我解决了我的问题!谢谢@JAM 我的问题:stackoverflow.com/questions/51731191/…
【解决方案2】:

看看NodeDir,有readFilesStream/promiseFiles等方法

【讨论】:

    猜你喜欢
    • 2017-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-15
    • 2023-04-07
    • 2013-03-22
    • 2013-11-05
    • 1970-01-01
    相关资源
    最近更新 更多