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,其值为第一个
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 stats.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