Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 25 additions & 1 deletion lib/internal/streams/duplexpair.js
Original file line number Diff line number Diff line change
Expand Up @@ -50,13 +50,37 @@ class DuplexSide extends Duplex {
this.#otherSide.on('end', callback);
this.#otherSide.push(null);
}


_destroy(err, callback) {
const otherSide = this.#otherSide;

if (otherSide !== null && !otherSide.destroyed) {
// Use nextTick to avoid crashing the current execution stack (like HTTP parser)
process.nextTick(() => {
if (otherSide.destroyed) return;

if (err) {
// Destroy the other side, without passing the 'err' object.
// This closes the other side gracefully so it doesn't hang,
// but prevents the "Unhandled error" crash.
otherSide.destroy();
} else {
// Standard graceful close
otherSide.push(null);
}
});
}

callback(err);
}
}

function duplexPair(options) {
const side0 = new DuplexSide(options);
const side1 = new DuplexSide(options);
side0[kInitOtherSide](side1);
side1[kInitOtherSide](side0);
return [ side0, side1 ];
return [side0, side1];
}
module.exports = duplexPair;
32 changes: 32 additions & 0 deletions test/parallel/test-duplex-error.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
'use strict';

const common = require('../common');
const assert = require('assert');
const { duplexPair } = require('stream');

const [sideA, sideB] = duplexPair();

// Side A should receive the error because we called .destroy(err) on it.
sideA.on('error', common.mustCall((err) => {
assert.strictEqual(err.message, 'Simulated error');
}));

// Side B should NOT necessarily emit an error (to avoid crashing
// existing code), but it MUST be destroyed.
sideB.on('error', common.mustNotCall('Side B should not emit an error event'));

sideB.on('close', common.mustCall(() => {
assert.strictEqual(sideB.destroyed, true);
}));

sideA.resume();
sideB.resume();

// Trigger the destruction
sideA.destroy(new Error('Simulated error'));

// Check the state in the next tick to allow nextTick/microtasks to run
setImmediate(common.mustCall(() => {
assert.strictEqual(sideA.destroyed, true);
assert.strictEqual(sideB.destroyed, true);
}));