diff --git a/lib/internal/streams/destroy.js b/lib/internal/streams/destroy.js index 76433594662d91..358422e12a33e0 100644 --- a/lib/internal/streams/destroy.js +++ b/lib/internal/streams/destroy.js @@ -272,9 +272,11 @@ function constructNT(stream) { } try { - stream._construct(onConstruct); + stream._construct((err) => { + process.nextTick(onConstruct, err); + }); } catch (err) { - onConstruct(err); + process.nextTick(onConstruct, err); } } diff --git a/test/parallel/test-stream2-transform.js b/test/parallel/test-stream2-transform.js index 849cfb3538b306..6f57384eb02443 100644 --- a/test/parallel/test-stream2-transform.js +++ b/test/parallel/test-stream2-transform.js @@ -468,3 +468,27 @@ const { PassThrough, Transform } = require('stream'); assert.strictEqual(ended, true); })); } + +{ + const s = new Transform({ + objectMode: true, + construct(callback) { + this.push('header from constructor'); + callback(); + }, + transform: (row, encoding, callback) => { + callback(null, row); + }, + }); + + const expected = [ + 'header from constructor', + 'firstLine', + 'secondLine', + ]; + s.on('data', common.mustCall((data) => { + assert.strictEqual(data.toString(), expected.shift()); + }, 3)); + s.write('firstLine'); + process.nextTick(() => s.write('secondLine')); +}