Skip to content

Commit 1317577

Browse files
rluvatondanielleadams
authored andcommitted
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 29ba98a commit 1317577

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
@@ -2477,21 +2477,44 @@ This method calls `fn` on each chunk of the stream in order, passing it the
24772477
result from the calculation on the previous element. It returns a promise for
24782478
the 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-
24842480
If no `initial` value is supplied the first chunk of the stream is used as the
24852481
initial value. If the stream is empty, the promise is rejected with a
24862482
`TypeError` with the `ERR_INVALID_ARGS` code property.
24872483

24882484
```mjs
24892485
import { 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

Comments
 (0)