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