@@ -2559,6 +2559,7 @@ it is important to ensure the correct handling of backpressure and errors.
25592559
25602560``` js
25612561const { once } = require (' events' );
2562+ const finished = util .promisify (stream .finished );
25622563
25632564const writable = fs .createWriteStream (' ./file' );
25642565
@@ -2570,26 +2571,45 @@ const writable = fs.createWriteStream('./file');
25702571 }
25712572 writable .end ();
25722573 // Ensure completion without errors.
2573- await once (writable, ' finish ' );
2574+ await finished (writable);
25742575})();
25752576```
25762577
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.
25792586
2580- Alternatively the readable stream could be wrapped with ` Readable.from() ` and
2587+ Alternatively, the readable stream could be wrapped with ` Readable.from() ` and
25812588then piped via ` .pipe() ` :
25822589
25832590``` js
2584- const { once } = require ( ' events ' );
2591+ const finished = util . promisify ( stream . finished );
25852592
25862593const writable = fs .createWriteStream (' ./file' );
25872594
25882595(async function () {
25892596 const readable = Readable .from (iterator);
25902597 readable .pipe (writable);
25912598 // 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);
25932613})();
25942614```
25952615
0 commit comments