1
假設我有一個readable
流,例如, request(URL)
。我想通過fs.createWriteStream()
將它的回覆寫在磁盤上,並在請求中填入管道。但同時我想通過crypto.createHash()
流來計算下載數據的校驗和。如何從一個流中讀取並一次寫入多個?
readable -+-> calc checksum
|
+-> write to disk
而且我想要在飛行中完成,而不是在內存中緩衝整個響應。
看來我可以使用oldschool on('data')
hook來實現它。下面的僞代碼:
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
這樣的東西,但我堅持實施。
謝謝!從文檔引用「可以將多個可寫流添加到單個可讀流中。」就是這個!我知道'pipe()',但它看起來像我錯過了這個設施。 –