11cb0ef41Sopenharmony_ci'use strict';
21cb0ef41Sopenharmony_ciconst common = require('../common');
31cb0ef41Sopenharmony_ci
41cb0ef41Sopenharmony_ci// Tests for the regression in _stream_writable discussed in
51cb0ef41Sopenharmony_ci// https://github.com/nodejs/node/pull/31756
61cb0ef41Sopenharmony_ci
71cb0ef41Sopenharmony_ci// Specifically, when a write callback is invoked synchronously
81cb0ef41Sopenharmony_ci// with an error, and autoDestroy is not being used, the error
91cb0ef41Sopenharmony_ci// should still be emitted on nextTick.
101cb0ef41Sopenharmony_ci
111cb0ef41Sopenharmony_ciconst { Writable } = require('stream');
121cb0ef41Sopenharmony_ci
131cb0ef41Sopenharmony_ciclass MyStream extends Writable {
141cb0ef41Sopenharmony_ci  #cb = undefined;
151cb0ef41Sopenharmony_ci
161cb0ef41Sopenharmony_ci  constructor() {
171cb0ef41Sopenharmony_ci    super({ autoDestroy: false });
181cb0ef41Sopenharmony_ci  }
191cb0ef41Sopenharmony_ci
201cb0ef41Sopenharmony_ci  _write(_, __, cb) {
211cb0ef41Sopenharmony_ci    this.#cb = cb;
221cb0ef41Sopenharmony_ci  }
231cb0ef41Sopenharmony_ci
241cb0ef41Sopenharmony_ci  close() {
251cb0ef41Sopenharmony_ci    // Synchronously invoke the callback with an error.
261cb0ef41Sopenharmony_ci    this.#cb(new Error('foo'));
271cb0ef41Sopenharmony_ci  }
281cb0ef41Sopenharmony_ci}
291cb0ef41Sopenharmony_ci
301cb0ef41Sopenharmony_ciconst stream = new MyStream();
311cb0ef41Sopenharmony_ci
321cb0ef41Sopenharmony_ciconst mustError = common.mustCall(2);
331cb0ef41Sopenharmony_ci
341cb0ef41Sopenharmony_cistream.write('test', () => {});
351cb0ef41Sopenharmony_ci
361cb0ef41Sopenharmony_ci// Both error callbacks should be invoked.
371cb0ef41Sopenharmony_ci
381cb0ef41Sopenharmony_cistream.on('error', mustError);
391cb0ef41Sopenharmony_ci
401cb0ef41Sopenharmony_cistream.close();
411cb0ef41Sopenharmony_ci
421cb0ef41Sopenharmony_ci// Without the fix in #31756, the error handler
431cb0ef41Sopenharmony_ci// added after the call to close will not be invoked.
441cb0ef41Sopenharmony_cistream.on('error', mustError);
45