@@ -2556,6 +2556,7 @@ it is important to ensure the correct handling of backpressure and errors.
25562556
25572557``` js
25582558const { once } = require (' events' );
2559+ const finished = util .promisify (stream .finished );
25592560
25602561const writable = fs .createWriteStream (' ./file' );
25612562
@@ -2567,26 +2568,45 @@ const writable = fs.createWriteStream('./file');
25672568 }
25682569 writable .end ();
25692570 // Ensure completion without errors.
2570- await once (writable, ' finish ' );
2571+ await finished (writable);
25712572})();
25722573```
25732574
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.
25762583
2577- Alternatively the readable stream could be wrapped with ` Readable.from() ` and
2584+ Alternatively, the readable stream could be wrapped with ` Readable.from() ` and
25782585then piped via ` .pipe() ` :
25792586
25802587``` js
2581- const { once } = require ( ' events ' );
2588+ const finished = util . promisify ( stream . finished );
25822589
25832590const writable = fs .createWriteStream (' ./file' );
25842591
25852592(async function () {
25862593 const readable = Readable .from (iterator);
25872594 readable .pipe (writable);
25882595 // 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);
25902610})();
25912611```
25922612
0 commit comments