@@ -2556,6 +2556,7 @@ it is important to ensure the correct handling of backpressure and errors.
2556
2556
2557
2557
``` js
2558
2558
const { once } = require (' events' );
2559
+ const finished = util .promisify (stream .finished );
2559
2560
2560
2561
const writable = fs .createWriteStream (' ./file' );
2561
2562
@@ -2567,26 +2568,45 @@ const writable = fs.createWriteStream('./file');
2567
2568
}
2568
2569
writable .end ();
2569
2570
// Ensure completion without errors.
2570
- await once (writable, ' finish ' );
2571
+ await finished (writable);
2571
2572
})();
2572
2573
```
2573
2574
2574
- In the above, errors on the write stream would be caught and thrown by the two
2575
- ` once() ` listeners, since ` once() ` will also handle ` 'error' ` events.
2575
+ In the above, errors on ` write() ` would be caught and thrown by the
2576
+ ` once() ` listener for the ` 'drain' ` event, since ` once() ` will also handle the
2577
+ ` 'error' ` event. To ensure completion of the write stream without errors,
2578
+ it is safer to use the ` finished() ` method as above, instead of using the
2579
+ ` once() ` listener for the ` 'finish' ` event. Under certain cases, an ` 'error' `
2580
+ event could be emitted by the writable stream after ` 'finish' ` and as ` once() `
2581
+ will release the ` 'error' ` handler on handling the ` 'finish' ` event, it could
2582
+ result in an unhandled error.
2576
2583
2577
- Alternatively the readable stream could be wrapped with ` Readable.from() ` and
2584
+ Alternatively, the readable stream could be wrapped with ` Readable.from() ` and
2578
2585
then piped via ` .pipe() ` :
2579
2586
2580
2587
``` js
2581
- const { once } = require ( ' events ' );
2588
+ const finished = util . promisify ( stream . finished );
2582
2589
2583
2590
const writable = fs .createWriteStream (' ./file' );
2584
2591
2585
2592
(async function () {
2586
2593
const readable = Readable .from (iterator);
2587
2594
readable .pipe (writable);
2588
2595
// Ensure completion without errors.
2589
- await once (writable, ' finish' );
2596
+ await finished (writable);
2597
+ })();
2598
+ ```
2599
+
2600
+ Or, using ` stream.pipeline() ` to pipe streams:
2601
+
2602
+ ``` js
2603
+ const pipeline = util .promisify (stream .pipeline );
2604
+
2605
+ const writable = fs .createWriteStream (' ./file' );
2606
+
2607
+ (async function () {
2608
+ const readable = Readable .from (iterator);
2609
+ await pipeline (readable, writable);
2590
2610
})();
2591
2611
```
2592
2612
0 commit comments