From 5d289d9a28c10b38f657222757062beaa1083660 Mon Sep 17 00:00:00 2001 From: Robert Nagy Date: Sun, 21 Jun 2020 16:40:29 +0200 Subject: [PATCH] stream: propagate write error to end callback Properly propagate all write errors throught to end callback. Fixes: https://github.com/nodejs/node/issues/33684 --- lib/_stream_writable.js | 14 +++++++++++-- .../test-stream-writable-end-cb-error.js | 20 +++++++++++++++++++ 2 files changed, 32 insertions(+), 2 deletions(-) diff --git a/lib/_stream_writable.js b/lib/_stream_writable.js index 916e9b87d9c17a..f3a8d63413a437 100644 --- a/lib/_stream_writable.js +++ b/lib/_stream_writable.js @@ -56,6 +56,7 @@ const { ERR_STREAM_WRITE_AFTER_END, ERR_UNKNOWN_ENCODING } = require('internal/errors').codes; +const { once } = require('internal/util'); const { errorOrDestroy } = destroyImpl; @@ -586,8 +587,17 @@ Writable.prototype.end = function(chunk, encoding, cb) { encoding = null; } - if (chunk !== null && chunk !== undefined) - this.write(chunk, encoding); + if (typeof cb === 'function') { + cb = once(cb); + } + + if (chunk != null) { + this.write(chunk, encoding, cb ? function(err) { + if (err) { + cb(err); + } + } : null); + } // .end() fully uncorks. if (state.corked) { diff --git a/test/parallel/test-stream-writable-end-cb-error.js b/test/parallel/test-stream-writable-end-cb-error.js index 24989a6d06a111..db3ff60f4e472a 100644 --- a/test/parallel/test-stream-writable-end-cb-error.js +++ b/test/parallel/test-stream-writable-end-cb-error.js @@ -46,3 +46,23 @@ const stream = require('stream'); writable.emit('error', new Error('kaboom')); })); } + +{ + // Invoke end with write error + const writable = new stream.Writable(); + + writable._write = (chunk, encoding, cb) => { + process.nextTick(cb); + }; + writable._final = (cb) => { + process.nextTick(cb); + }; + + writable.end(); + writable.end('asd', common.mustCall((err) => { + assert.strictEqual(err.code, 'ERR_STREAM_WRITE_AFTER_END'); + })); + writable.on('error', common.mustCall((err) => { + assert.strictEqual(err.code, 'ERR_STREAM_WRITE_AFTER_END'); + })); +}