readable.reduce(fn[, initial[, options]])


稳定性: 1 - 实验性

  • fn <Function> | <AsyncFunction> 一个用于对流中的每个数据块进行调用的归约函数。
    • previous <any> 从最后一次调用 fn 获得的值,或者如果指定了则为 initial 值,否则为流的第一个块。
    • data <any> 来自流的一段数据。
    • options <Object>
      • signal <AbortSignal> 如果流被销毁,则会中止,从而允许提前终止 fn 调用。
  • initial <any> 在归约中使用的初始值。
  • options <Object>
  • 返回:<Promise> 对减值最终金额的承诺。

此方法按顺序对流的每个块调用 fn,将前一个元素计算的结果传递给它。它返回一个表示归约最终值的 Promise。

🌐 This method calls fn on each chunk of the stream in order, passing it the result from the calculation on the previous element. It returns a promise for the final value of the reduction.

如果未提供 initial 值,则流的第一个数据块将用作初始值。如果流为空,Promise 将被拒绝,并返回一个 TypeError,其 code 属性为 ERR_INVALID_ARGS

🌐 If no initial value is supplied the first chunk of the stream is used as the initial value. If the stream is empty, the promise is rejected with a TypeError with the ERR_INVALID_ARGS code property.

import { Readable } from 'node:stream';
import { readdir, stat } from 'node:fs/promises';
import { join } from 'node:path';

const directoryPath = './src';
const filesInDir = await readdir(directoryPath);

const folderSize = await Readable.from(filesInDir)
  .reduce(async (totalSize, file) => {
    const { size } = await stat(join(directoryPath, file));
    return totalSize + size;
  }, 0);

console.log(folderSize); 

reducer 函数逐元素迭代流,这意味着没有 concurrency 参数或并行处理。要并发执行 reduce,你可以将异步函数提取到 readable.map 方法中。

🌐 The reducer function iterates the stream element-by-element which means that there is no concurrency parameter or parallelism. To perform a reduce concurrently, you can extract the async function to readable.map method.

import { Readable } from 'node:stream';
import { readdir, stat } from 'node:fs/promises';
import { join } from 'node:path';

const directoryPath = './src';
const filesInDir = await readdir(directoryPath);

const folderSize = await Readable.from(filesInDir)
  .map((file) => stat(join(directoryPath, file)), { concurrency: 2 })
  .reduce((totalSize, { size }) => totalSize + size, 0);

console.log(folderSize);