@@ -2499,21 +2499,44 @@ This method calls `fn` on each chunk of the stream in order, passing it the |
2499 | 2499 | result from the calculation on the previous element. It returns a promise for |
2500 | 2500 | the final value of the reduction. |
2501 | 2501 |
|
2502 | | -The reducer function iterates the stream element-by-element which means that |
2503 | | -there is no `concurrency` parameter or parallelism. To perform a `reduce` |
2504 | | -concurrently, it can be chained to the [`readable.map`][] method. |
2505 | | - |
2506 | 2502 | If no `initial` value is supplied the first chunk of the stream is used as the |
2507 | 2503 | initial value. If the stream is empty, the promise is rejected with a |
2508 | 2504 | `TypeError` with the `ERR_INVALID_ARGS` code property. |
2509 | 2505 |
|
2510 | 2506 | ```mjs |
2511 | 2507 | import { Readable } from 'node:stream'; |
| 2508 | +import { readdir, stat } from 'node:fs/promises'; |
| 2509 | +import { join } from 'node:path'; |
2512 | 2510 |
|
2513 | | -const ten = await Readable.from([1, 2, 3, 4]).reduce((previous, data) => { |
2514 | | - return previous + data; |
2515 | | -}); |
2516 | | -console.log(ten); // 10 |
| 2511 | +const directoryPath = './src'; |
| 2512 | +const filesInDir = await readdir(directoryPath); |
| 2513 | + |
| 2514 | +const folderSize = await Readable.from(filesInDir) |
| 2515 | + .reduce(async (totalSize, file) => { |
| 2516 | + const { size } = await stat(join(directoryPath, file)); |
| 2517 | + return totalSize + size; |
| 2518 | + }, 0); |
| 2519 | + |
| 2520 | +console.log(folderSize); |
| 2521 | +``` |
| 2522 | + |
| 2523 | +The reducer function iterates the stream element-by-element which means that |
| 2524 | +there is no `concurrency` parameter or parallelism. To perform a `reduce` |
| 2525 | +concurrently, you can extract the async function to [`readable.map`][] method. |
| 2526 | + |
| 2527 | +```mjs |
| 2528 | +import { Readable } from 'node:stream'; |
| 2529 | +import { readdir, stat } from 'node:fs/promises'; |
| 2530 | +import { join } from 'node:path'; |
| 2531 | + |
| 2532 | +const directoryPath = './src'; |
| 2533 | +const filesInDir = await readdir(directoryPath); |
| 2534 | + |
| 2535 | +const folderSize = await Readable.from(filesInDir) |
| 2536 | + .map((file) => stat(join(directoryPath, file)), { concurrency: 2 }) |
| 2537 | + .reduce((totalSize, { size }) => totalSize + size, 0); |
| 2538 | + |
| 2539 | +console.log(folderSize); |
2517 | 2540 | ``` |
2518 | 2541 |
|
2519 | 2542 | ### Duplex and transform streams |
|