readable.flatMap(fn[, options])
稳定性: 1 - 实验性
fn<Function> | <AsyncGeneratorFunction> | <AsyncFunction> 是一个函数,用于映射流中的每个数据块。data<any> 从流中获取一块数据。options<Object>signal<AbortSignal> 如果流被销毁则中止,从而允许提前中止fn调用。
options<Object>concurrency<number> 是fn在流上同时调用的最大并发次数。默认值:1。signal<AbortSignal> 允许在信号被中止时销毁流。
- 返回:<Readable> 一个通过函数
fn执行平铺映射的流。
此方法通过对流的每个块应用给定的回调函数,然后将结果展平成一个新的流,从而返回一个新流。
【This method returns a new stream by applying the given callback to each chunk of the stream and then flattening the result.】
可以从 fn 返回一个流或其他可迭代对象或异步可迭代对象,结果流将被合并(扁平化)到返回的流中。
【It is possible to return a stream or another iterable or async iterable from
fn and the result streams will be merged (flattened) into the returned
stream.】
import { Readable } from 'node:stream';
import { createReadStream } from 'node:fs';
// With a synchronous mapper.
for await (const chunk of Readable.from([1, 2, 3, 4]).flatMap((x) => [x, x])) {
console.log(chunk); // 1, 1, 2, 2, 3, 3, 4, 4
}
// With an asynchronous mapper, combine the contents of 4 files
const concatResult = Readable.from([
'./1.mjs',
'./2.mjs',
'./3.mjs',
'./4.mjs',
]).flatMap((fileName) => createReadStream(fileName));
for await (const result of concatResult) {
// This will contain the contents (all chunks) of all 4 files
console.log(result);
}