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
展平映射的流。
此方法通过将给定的回调应用到流的每个块然后展平结果来返回新的流。
可以从 fn
返回流或另一个迭代或异步迭代,结果流将被合并(展平)到返回的流中。
import { Readable } from 'node:stream';
import { createReadStream } from 'node:fs';
// 使用同步映射器。
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
}
// 使用异步的映射器,合并 4 个文件的内容
const concatResult = Readable.from([
'./1.mjs',
'./2.mjs',
'./3.mjs',
'./4.mjs',
]).flatMap((fileName) => createReadStream(fileName));
for await (const result of concatResult) {
// 这将包含所有 4 个文件的内容(所有块)
console.log(result);
}
Stability: 1 - Experimental
fn
<Function> | <AsyncGeneratorFunction> | <AsyncFunction> a function to map over every chunk in the stream.data
<any> a chunk of data from the stream.options
<Object>signal
<AbortSignal> aborted if the stream is destroyed allowing to abort thefn
call early.
options
<Object>concurrency
<number> the maximum concurrent invocation offn
to call on the stream at once. Default:1
.signal
<AbortSignal> allows destroying the stream if the signal is aborted.
- 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.
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);
}