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 调用的等待返回值为真值,则流就会被销毁,并且 promise 使用 fn 返回真值的值来履行。 如果对块的所有 fn 调用都返回非真值,则 promise 使用 undefined 履行。

import { Readable } from 'node:stream';
import { stat } from 'node:fs/promises';

// 使用同步谓词。
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

// 使用异步谓词,一次最多进行 2 个文件检查。
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); // 大文件的文件名,如果列表中有大于 1MB 的文件
console.log('done'); // 流已结束

Stability: 1 - Experimental

  • fn <Function> | <AsyncFunction> a function to call on each chunk of the stream.
    • data <any> a chunk of data from the stream.
    • options <Object>
      • signal <AbortSignal> aborted if the stream is destroyed allowing to abort the fn call early.
  • options <Object>
    • concurrency <number> the maximum concurrent invocation of fn to call on the stream at once. Default: 1.
    • signal <AbortSignal> allows destroying the stream if the signal is aborted.
  • Returns: <Promise> a promise evaluating to the first chunk for which fn evaluated with a truthy value, or undefined if no element was found.

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