stream.finished(stream[, options], callback)
-
stream
<Stream> | <ReadableStream> | <WritableStream> 可读和/或可写流/网络流。¥
stream
<Stream> | <ReadableStream> | <WritableStream> A readable and/or writable stream/webstream. -
options
<Object>-
error
<boolean> 如果设置为false
,则对emit('error', err)
的调用不会被视为已完成。默认值:true
。¥
error
<boolean> If set tofalse
, then a call toemit('error', err)
is not treated as finished. Default:true
. -
readable
<boolean> 当设置为false
时,即使流可能仍然可读,也会在流结束时调用回调。默认值:true
。¥
readable
<boolean> When set tofalse
, the callback will be called when the stream ends even though the stream might still be readable. Default:true
. -
writable
<boolean> 当设置为false
时,即使流可能仍可写,也会在流结束时调用回调。默认值:true
。¥
writable
<boolean> When set tofalse
, the callback will be called when the stream ends even though the stream might still be writable. Default:true
. -
signal
<AbortSignal> 允许中止等待流完成。如果信号被中止,底层流将不会被中止。将使用AbortError
调用回调。此函数添加的所有已注册监听器也将被删除。¥
signal
<AbortSignal> allows aborting the wait for the stream finish. The underlying stream will not be aborted if the signal is aborted. The callback will get called with anAbortError
. All registered listeners added by this function will also be removed.
-
-
callback
<Function> 采用可选的错误参数的回调函数。¥
callback
<Function> A callback function that takes an optional error argument. -
返回:<Function> 清除所有已注册监听器的函数。
¥Returns: <Function> A cleanup function which removes all registered listeners.
当流不再可读、不可写或遇到错误或过早关闭事件时获得通知的函数。
¥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.
stream.finished()
在调用 callback
后离开悬空事件监听器(特别是 'error'
、'end'
、'finish'
和 'close'
)。这样做的原因是意外的 'error'
事件(由于不正确的流实现)不会导致意外的崩溃。如果这是不需要的行为,则需要在回调中调用返回的清理函数:
¥stream.finished()
leaves dangling event listeners (in particular
'error'
, 'end'
, 'finish'
and 'close'
) after callback
has been
invoked. The reason for this is so that unexpected 'error'
events (due to
incorrect stream implementations) do not cause unexpected crashes.
If this is unwanted behavior then the returned cleanup function needs to be
invoked in the callback:
const cleanup = finished(rs, (err) => {
cleanup();
// ...
});