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

标签 node.js node-streams

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

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

最佳答案

一种方法是生成 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.');

关于node.js - 等待所有流完成 - 流式传输文件目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37229725/

相关文章:

node.js - NodeJS SetInterval 与 Async/Await

node.js - 使用 ISO 格式的日期作为字典中的键来解析/MongoDB

html - 使用Vue Javascript将JSON数据提取到html文件中的表中时出现问题

javascript - underscore js findWhere 查找只有键值的对象

javascript - 仅当收到 HTTP 200 时如何通过 pipe() npm-request?

node.js - 如果我们将nodejs进程放入docker容器中,会对性能产生什么影响?

node.js - 为什么尝试写入大文件会导致 js 堆内存不足

Node.js:当子进程在对其标准输入流进行大量写入操作期间突然关闭时,会引发无法捕获的错误

Node.js 将文本作为 `spawnSync` 的标准输入传递