readable.find(fn[, options])
¥Stability: 1 - Experimental
-
fn
<Function> | <AsyncFunction> 调用流的每个块的函数。¥
fn
<Function> | <AsyncFunction> a function to call on each chunk of the stream.-
data
<any> 来自流的数据块。¥
data
<any> a chunk of data from the stream. -
options
<Object>-
signal
<AbortSignal> 如果流被销毁则中止,允许提前中止fn
调用。¥
signal
<AbortSignal> aborted if the stream is destroyed allowing to abort thefn
call early.
-
-
-
options
<Object>-
concurrency
<number> 一次调用流的fn
的最大并发调用数。默认值:1
。¥
concurrency
<number> the maximum concurrent invocation offn
to call on the stream at once. Default:1
. -
signal
<AbortSignal> 如果信号中止,允许销毁流。¥
signal
<AbortSignal> allows destroying the stream if the signal is aborted.
-
-
返回:<Promise> 是评估第一个块的 promise,其中
fn
使用真值进行评估,如果未找到元素,则评估undefined
。¥Returns: <Promise> a promise evaluating to the first chunk for which
fn
evaluated with a truthy value, orundefined
if no element was found.
此方法类似于 Array.prototype.find
,并在流中的每个块上调用 fn
以查找具有 fn
真值的块。一旦 fn
调用的等待返回值是真实的,流就会被销毁,并且 promise 会用 fn
返回真实值的值来实现。如果对块的所有 fn
调用都返回一个假值,则 promise 通过 undefined
实现。
¥This method is similar to Array.prototype.find
and calls fn
on each chunk
in the stream to find a chunk with a truthy value for fn
. Once an fn
call's
awaited return value is truthy, the stream is destroyed and the promise is
fulfilled with value for which fn
returned a truthy value. If all of the
fn
calls on the chunks return a falsy value, the promise is fulfilled with
undefined
.
import { Readable } from 'node:stream';
import { stat } from 'node:fs/promises';
// With a synchronous predicate.
await Readable.from([1, 2, 3, 4]).find((x) => x > 2); // 3
await Readable.from([1, 2, 3, 4]).find((x) => x > 0); // 1
await Readable.from([1, 2, 3, 4]).find((x) => x > 10); // undefined
// With an asynchronous predicate, making at most 2 file checks at a time.
const foundBigFile = await Readable.from([
'file1',
'file2',
'file3',
]).find(async (fileName) => {
const stats = await stat(fileName);
return stat.size > 1024 * 1024;
}, { concurrency: 2 });
console.log(foundBigFile); // File name of large file, if any file in the list is bigger than 1MB
console.log('done'); // Stream has finished