readable.find(fn[, options])
稳定性: 1 - 实验性
fn<Function> | <AsyncFunction> 是一个在流的每个数据块上调用的函数。data<any> 从流中获取一块数据。options<Object>signal<AbortSignal> 如果流被销毁则中止,从而允许提前中止fn调用。
options<Object>concurrency<number> 是fn在流上同时调用的最大并发次数。默认值:1。signal<AbortSignal> 允许在信号被中止时销毁流。
- 返回:<Promise> 一个 promise,该 promise 会返回第一个经过
fn评估为真值的块,如果未找到任何元素,则返回undefined。
此方法类似于 Array.prototype.find,会在流中的每个块上调用 fn,以查找 fn 返回真值的块。一旦某次 fn 调用的 await 返回值为真,流将被销毁,并且该 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