如何在 Node Js 中处理多个流?
How to handle mutiple streams in Nodejs?
我正在编写图像处理服务,我必须将图像转换成多种尺寸
const writable1 = storage(name1).writableStream();
const writable2 = storage(name2).writableStream();
const writable3 = storage(name3).writableStream();
//piping the file stream to their respective storage stream
file.stream.pipe(imageTransformer).pipe(writable1);
file.stream.pipe(imageTransformer).pipe(writable2);
file.stream.pipe(imageTransformer).pipe(writable3);
我想知道所有流何时完成写入目标
现在我只检查了一个流,例如:
writable3.on('finish', callback);
//error handling
writable3.on('error', callback);
我见过像 https://github.com/mafintosh/pump
和 https://github.com/maxogden/mississippi
这样的库,但这些库只显示写入具有多个转换的单个目标。
我怎样才能检查是否所有的流都写完了或者其中一个流出错了?我如何在数组中处理它们?
您可以使用组合转换流来承诺和 Promise.all
。
在示例中,我使用了 stream-to-promise 流的库来保证转换。
对于每个流,都会创建一个承诺。 promise 在流完成时解析,在流失败时拒绝。
const streamToPromise = require('stream-to-promise')
const promise1 = streamToPromise(readable1.pipe(writable1));
const promise2 = streamToPromise(readable2.pipe(writable2));
Promise.all([promise1, promise2]).
.then(() => console.log('all the streams are finished'));
我正在编写图像处理服务,我必须将图像转换成多种尺寸
const writable1 = storage(name1).writableStream();
const writable2 = storage(name2).writableStream();
const writable3 = storage(name3).writableStream();
//piping the file stream to their respective storage stream
file.stream.pipe(imageTransformer).pipe(writable1);
file.stream.pipe(imageTransformer).pipe(writable2);
file.stream.pipe(imageTransformer).pipe(writable3);
我想知道所有流何时完成写入目标
现在我只检查了一个流,例如:
writable3.on('finish', callback);
//error handling
writable3.on('error', callback);
我见过像 https://github.com/mafintosh/pump
和 https://github.com/maxogden/mississippi
这样的库,但这些库只显示写入具有多个转换的单个目标。
我怎样才能检查是否所有的流都写完了或者其中一个流出错了?我如何在数组中处理它们?
您可以使用组合转换流来承诺和 Promise.all
。
在示例中,我使用了 stream-to-promise 流的库来保证转换。
对于每个流,都会创建一个承诺。 promise 在流完成时解析,在流失败时拒绝。
const streamToPromise = require('stream-to-promise') const promise1 = streamToPromise(readable1.pipe(writable1)); const promise2 = streamToPromise(readable2.pipe(writable2)); Promise.all([promise1, promise2]). .then(() => console.log('all the streams are finished'));