8000
We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent 8a69929 commit 908798aCopy full SHA for 908798a
doc/api/stream.md
@@ -2499,21 +2499,44 @@ This method calls `fn` on each chunk of the stream in order, passing it the
2499
result from the calculation on the previous element. It returns a promise for
2500
the final value of the reduction.
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
If no `initial` value is supplied the first chunk of the stream is used as the
2507
initial value. If the stream is empty, the promise is rejected with a
2508
`TypeError` with the `ERR_INVALID_ARGS` code property.
2509
2510
```mjs
2511
import { Readable } from 'node:stream';
+import { readdir, stat } from 'node:fs/promises';
+import { join } from 'node:path';
2512
2513
-const ten = await Readable.from([1, 2, 3, 4]).reduce((previous, data) => {
2514
- return previous + data;
2515
-});
2516
-console.log(ten); // 10
+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));
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
2530
2531
2532
2533
2534
2535
2536
+ .map((file) => stat(join(directoryPath, file)), { concurrency: 2 })
2537
+ .reduce((totalSize, { size }) => totalSize + size, 0);
2538
2539
2540
```
2541
2542
### Duplex and transform streams