ber*_*erg 10 node.js node-streams
我使用client.upload在pkgcloud上传文件的目录.所有流完成后执行回调的最佳方法是什么?是否有一种内置方式来注册每个流的"完成"事件并在它们全部被触发后执行回调?
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);
}
Run Code Online (Sandbox Code Playgroud)
JAM*_*JAM 22
一种方法是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.'); });
Run Code Online (Sandbox Code Playgroud)
或者,如果您有权访问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.');
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6848 次 |
| 最近记录: |