| FazBrowse GitHub Viewer | Trending | | Home |
| Tools: [Download Repo ZIP] [Original HTTPS Page] |
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
@@ -2477,21 +2477,44 @@ This method calls `fn` on each chunk of the stream in order, passing it the | |||
| 2477 | 2477 | result from the calculation on the previous element. It returns a promise for | |
| 2478 | 2478 | the final value of the reduction. | |
| 2479 | 2479 | ||
| 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 | - | ||
| 2484 | 2480 | If no `initial` value is supplied the first chunk of the stream is used as the | |
| 2485 | 2481 | initial value. If the stream is empty, the promise is rejected with a | |
| 2486 | 2482 | `TypeError` with the `ERR_INVALID_ARGS` code property. | |
| 2487 | 2483 | ||
| 2488 | 2484 | ```mjs | |
| 2489 | 2485 | import { Readable } from 'node:stream'; | |
| 2486 | + import { readdir, stat } from 'node:fs/promises'; | ||
| 2487 | + import { join } from 'node:path'; | ||
| 2490 | 2488 | ||
| 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); | ||
| 2495 | 2518 | ``` | |
| 2496 | 2519 | ||
| 2497 | 2520 | ### Duplex and transform streams | |
| Back | FazBrowse Home | New Git URL |
0 commit comments