readable.map(fn[, options])


稳定性: 1 - 实验性的

¥Stability: 1 - Experimental

  • fn <Function> | <AsyncFunction> 映射流中每个块的函数。

    ¥fn <Function> | <AsyncFunction> a function to map over every chunk in 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 the fn call early.

  • options <Object>

    • concurrency <number> 一次调用流的 fn 的最大并发调用数。默认值:1

      ¥concurrency <number> the maximum concurrent invocation of fn to call on the stream at once. Default: 1.

    • highWaterMark <number> 在等待用户消耗映射项目时要缓冲多少项目。默认值:concurrency * 2 - 1

      ¥highWaterMark <number> how many items to buffer while waiting for user consumption of the mapped items. Default: concurrency * 2 - 1.

    • signal <AbortSignal> 如果信号中止,允许销毁流。

      ¥signal <AbortSignal> allows destroying the stream if the signal is aborted.

  • 返回:<Readable> 是用函数 fn 映射的流。

    ¥Returns: <Readable> a stream mapped with the function fn.

此方法允许在流上进行映射。将为流中的每个块调用 fn 函数。如果 fn 函数返回一个 promise - 该 promise 在传递到结果流之前将被 await

¥This method allows mapping over the stream. The fn function will be called for every chunk in the stream. If the fn function returns a promise - that promise will be awaited before being passed to the result stream.

import { Readable } from 'node:stream';
import { Resolver } from 'node:dns/promises';

// With a synchronous mapper.
for await (const chunk of Readable.from([1, 2, 3, 4]).map((x) => x * 2)) {
  console.log(chunk); // 2, 4, 6, 8
}
// With an asynchronous mapper, making at most 2 queries at a time.
const resolver = new Resolver();
const dnsResults = Readable.from([
  'nodejs.org',
  'openjsf.org',
  'www.linuxfoundation.org',
]).map((domain) => resolver.resolve4(domain), { concurrency: 2 });
for await (const result of dnsResults) {
  console.log(result); // Logs the DNS result of resolver.resolve4.
}