stream.finished(stream[, options], callback)
stream<Stream> 一个可读和/或可写的流。options<Object>error<boolean> 如果设置为false,则调用emit('error', err)不会被视为完成。默认值:true。readable<boolean> 当设置为false时,即使流仍然可读,也会在流结束时调用回调。默认值:true。writable<boolean> 当设置为false时,即使流仍然可写,也会在流结束时调用回调。默认值:true。signal<AbortSignal> 允许中止等待流完成。如果信号被中止,底层流不会被中止。回调函数会被调用,并带有AbortError。所有通过此函数添加的已注册监听器也将被移除。
callback<Function> 一个可选接收错误参数的回调函数。- 返回:<Function> 一个清理函数,用于移除所有注册的监听器。
一个用于在流不再可读、不可写或发生错误或提前关闭事件时接收通知的函数。
🌐 A function to get notified when a stream is no longer readable, writable or has experienced an error or a premature close event.
const { finished } = require('node:stream');
const fs = require('node:fs');
const rs = fs.createReadStream('archive.tar');
finished(rs, (err) => {
if (err) {
console.error('Stream failed.', err);
} else {
console.log('Stream is done reading.');
}
});
rs.resume(); // Drain the stream. 在错误处理场景中尤其有用,例如流被提前销毁(如中止的 HTTP 请求),并且不会触发 'end' 或 'finish'。
🌐 Especially useful in error handling scenarios where a stream is destroyed
prematurely (like an aborted HTTP request), and will not emit 'end'
or 'finish'.
finished API 提供了 promise 版本:
🌐 The finished API provides promise version:
const { finished } = require('node:stream/promises');
const fs = require('node:fs');
const rs = fs.createReadStream('archive.tar');
async function run() {
await finished(rs);
console.log('Stream is done reading.');
}
run().catch(console.error);
rs.resume(); // Drain the stream. stream.finished() 在调用 callback 后会留下悬挂的事件监听器(特别是 'error'、'end'、'finish' 和 'close')。这样做的原因是为了防止由于流实现不正确而导致的意外 'error' 事件引起程序意外崩溃。如果不希望出现这种行为,则需要在回调中调用返回的清理函数:
const cleanup = finished(rs, (err) => {
cleanup();
// ...
});