From 33424e6d5229afc9df5e0634760b19fd0dbf4597 Mon Sep 17 00:00:00 2001 From: Robert Nagy Date: Tue, 13 Apr 2021 00:54:24 +0200 Subject: [PATCH] stream: fix multiple Writable.destroy() calls Calling Writable.destroy() multiple times in the same tick could cause an assertion error. Fixes: https://github.com/nodejs/node/issues/38189 PR-URL: https://github.com/nodejs/node/pull/38221 Reviewed-By: Matteo Collina Reviewed-By: Luigi Pinca Reviewed-By: Nitzan Uziely Reviewed-By: Rich Trott Backport-PR-URL: https://github.com/nodejs/node/pull/38473 --- lib/internal/streams/writable.js | 6 +++++- test/parallel/test-stream-writable-destroy.js | 11 +++++++++++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/lib/internal/streams/writable.js b/lib/internal/streams/writable.js index fbc0532681b83d..26e5ae6d25e7c8 100644 --- a/lib/internal/streams/writable.js +++ b/lib/internal/streams/writable.js @@ -770,7 +770,11 @@ ObjectDefineProperties(Writable.prototype, { const destroy = destroyImpl.destroy; Writable.prototype.destroy = function(err, cb) { const state = this._writableState; - if (!state.destroyed) { + + // Invoke pending callbacks. + if (!state.destroyed && + (state.bufferedIndex < state.buffered.length || + state[kOnFinished].length)) { process.nextTick(errorBuffer, state, new ERR_STREAM_DESTROYED('write')); } destroy.call(this, err, cb); diff --git a/test/parallel/test-stream-writable-destroy.js b/test/parallel/test-stream-writable-destroy.js index 9f6136923ee176..f3ca402d5b3f94 100644 --- a/test/parallel/test-stream-writable-destroy.js +++ b/test/parallel/test-stream-writable-destroy.js @@ -417,3 +417,14 @@ const assert = require('assert'); })); write.write('asd'); } + +{ + // Destroy twice + const write = new Writable({ + write(chunk, enc, cb) { cb(); } + }); + + write.end(common.mustCall()); + write.destroy(); + write.destroy(); +}