readable.map(fn[, options])
稳定性: 1 - 实验性
fn<Function> | <AsyncFunction> 是一个可以对流中的每个区块进行映射的函数。data<any> 从流中获取一块数据。options<Object>signal<AbortSignal> 如果流被销毁则中止,从而允许提前中止fn调用。
options<Object>concurrency<number> 是fn在流上同时调用的最大并发次数。默认值:1。highWaterMark<number> 在等待用户消费映射后的项时要缓冲的项目数量。默认值:concurrency * 2 - 1。signal<AbortSignal> 允许在信号被中止时销毁流。
- 返回:<Readable> 一个使用函数
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.
}