Skip to content

Commit c588145

Browse files
authored
doc: update stream.reduce concurrency note
PR-URL: #47166 Reviewed-By: Matteo Collina <matteo.collina@gmail.com> Reviewed-By: Mohammed Keyvanzadeh <mohammadkeyvanzade94@gmail.com>
1 parent 8e203f1 commit c588145

File tree

1 file changed

+31
-8
lines changed

1 file changed

+31
-8
lines changed

doc/api/stream.md

+31-8
Original file line numberDiff line numberDiff line change
@@ -2501,21 +2501,44 @@ This method calls `fn` on each chunk of the stream in order, passing it the
25012501
result from the calculation on the previous element. It returns a promise for
25022502
the final value of the reduction.
25032503

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-
25082504
If no `initial` value is supplied the first chunk of the stream is used as the
25092505
initial value. If the stream is empty, the promise is rejected with a
25102506
`TypeError` with the `ERR_INVALID_ARGS` code property.
25112507

25122508
```mjs
25132509
import { Readable } from 'node:stream';
2510+
import { readdir, stat } from 'node:fs/promises';
2511+
import { join } from 'node:path';
25142512

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);
25192542
```
25202543

25212544
### Duplex and transform streams

0 commit comments

Comments
 (0)