readable.flatMap(fn[, options])
¥Stability: 1 - Experimental
-
fn
<Function> | <AsyncGeneratorFunction> | <AsyncFunction> 映射流中每个块的函数。¥
fn
<Function> | <AsyncGeneratorFunction> | <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 thefn
call early.
-
-
-
options
<Object>-
concurrency
<number> 一次调用流的fn
的最大并发调用数。默认值:1
。¥
concurrency
<number> the maximum concurrent invocation offn
to call on the stream at once. Default:1
. -
signal
<AbortSignal> 如果信号中止,允许销毁流。¥
signal
<AbortSignal> allows destroying the stream if the signal is aborted.
-
-
返回:<Readable> 是使用函数
fn
进行扁平映射的流。¥Returns: <Readable> a stream flat-mapped with the function
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);
}