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