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

wqnecbli  于 2023-05-17  发布在  Node.js
关注(0)|答案(2)|浏览(198)

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

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

1hdlvixo1#

一种方法是为每次上传生成一个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.');
6kkfgxo0

6kkfgxo02#

看看NodeDir,它有像readFilesStream/promiseFiles等方法。

相关问题