如何从一个stream中读取并一次写入多个?

假设我有一个readablestream,例如request(URL) 。 我想通过fs.createWriteStream()将请求的响应写在磁盘上, 但同时我想通过crypto.createHash()stream来计算下载数据的校验和。

 readable -+-> calc checksum | +-> write to disk 

我想在飞行中完成,而不是在内存中缓冲整个响应。

看来我可以on('data')钩子on('data')使用oldschool来实现它。 下面的伪代码:

 const hashStream = crypto.createHash('sha256'); hashStream.on('error', cleanup); const dst = fs.createWriteStream('...'); dst.on('error', cleanup); request(...).on('data', (chunk) => { hashStream.write(chunk); dst.write(chunk); }).on('end', () => { hashStream.end(); const checksum = hashStream.read(); if (checksum != '...') { cleanup(); } else { dst.end(); } }).on('error', cleanup); function cleanup() { /* cancel streams, erase file */ }; 

但是这种方法看起来很尴尬。 我试图使用stream.Writablestream.Writable来实现类似read | calc + echo | write东西 read | calc + echo | write read | calc + echo | write但我坚持实施。

Node.js可读stream有一个.pipe方法,其工作方式与Unixpipe道运算符非常相似,不同之处在于您可以stream式传输js对象以及某种types的string。

这是一个到pipe道上的文档的链接

在你的情况下使用的例子可能是这样的:

 const req = request(...); req.pipe(dst); req.pipe(hash); 

请注意,您仍然必须处理每个stream的错误,因为它们没有被传播,并且如果可读的错误,目标不会被closures。