@@ -2477,21 +2477,44 @@ This method calls `fn` on each chunk of the stream in order, passing it the
24772477result from the calculation on the previous element. It returns a promise for
24782478the final value of the reduction.
24792479
2480- The reducer function iterates the stream element-by-element which means that
2481- there is no ` concurrency ` parameter or parallelism. To perform a ` reduce `
2482- concurrently, it can be chained to the [ ` readable.map ` ] [ ] method.
2483-
24842480If no ` initial ` value is supplied the first chunk of the stream is used as the
24852481initial value. If the stream is empty, the promise is rejected with a
24862482` TypeError ` with the ` ERR_INVALID_ARGS ` code property.
24872483
24882484``` mjs
24892485import { Readable } from ' node:stream' ;
2486+ import { readdir , stat } from ' node:fs/promises' ;
2487+ import { join } from ' node:path' ;
24902488
2491- const ten = await Readable .from ([1 , 2 , 3 , 4 ]).reduce ((previous , data ) => {
2492- return previous + data;
2493- });
2494- console .log (ten); // 10
2489+ const directoryPath = ' ./src' ;
2490+ const filesInDir = await readdir (directoryPath);
2491+
2492+ const folderSize = await Readable .from (filesInDir)
2493+ .reduce (async (totalSize , file ) => {
2494+ const { size } = await stat (join (directoryPath, file));
2495+ return totalSize + size;
2496+ }, 0 );
2497+
2498+ console .log (folderSize);
2499+ ```
2500+
2501+ The reducer function iterates the stream element-by-element which means that
2502+ there is no ` concurrency ` parameter or parallelism. To perform a ` reduce `
2503+ concurrently, you can extract the async function to [ ` readable.map ` ] [ ] method.
2504+
2505+ ``` mjs
2506+ import { Readable } from ' node:stream' ;
2507+ import { readdir , stat } from ' node:fs/promises' ;
2508+ import { join } from ' node:path' ;
2509+
2510+ const directoryPath = ' ./src' ;
2511+ const filesInDir = await readdir (directoryPath);
2512+
2513+ const folderSize = await Readable .from (filesInDir)
2514+ .map ((file ) => stat (join (directoryPath, file)), { concurrency: 2 })
2515+ .reduce ((totalSize , { size }) => totalSize + size, 0 );
2516+
2517+ console .log (folderSize);
24952518```
24962519
24972520### Duplex and transform streams
0 commit comments