【发布时间】:2017-08-27 12:22:34
【问题描述】:
假设我有一个readable 流,例如request(URL)。我想通过fs.createWriteStream() 将它的响应写在磁盘上,并通过管道发送请求。但同时我想通过crypto.createHash()流计算下载数据的校验和。
readable -+-> calc checksum
|
+-> write to disk
而且我想在运行中完成它,而不是在内存中缓冲整个响应。
看来我可以使用 oldschool on('data') 钩子来实现它。伪代码如下:
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.Transform 或stream.Writable 来实现read | calc + echo | write 之类的东西,但我坚持执行。
【问题讨论】:
标签: javascript node.js pipeline node-streams