@@ -458,6 +458,11 @@ function onwriteError(stream, state, er, cb) {
458458 -- state . pendingcb ;
459459
460460 cb ( er ) ;
461+ // Ensure callbacks are invoked even when autoDestroy is
462+ // not enabled. Passing `er` here doesn't make sense since
463+ // it's related to one specific write, not to the buffered
464+ // writes.
465+ errorBuffer ( state , new ERR_STREAM_DESTROYED ( 'write' ) ) ;
461466 // This can emit error, but error must always follow cb.
462467 errorOrDestroy ( stream , er ) ;
463468}
@@ -531,9 +536,29 @@ function afterWrite(stream, state, count, cb) {
531536 cb ( ) ;
532537 }
533538
539+ if ( state . destroyed ) {
540+ errorBuffer ( state , new ERR_STREAM_DESTROYED ( 'write' ) ) ;
541+ }
542+
534543 finishMaybe ( stream , state ) ;
535544}
536545
546+ // If there's something in the buffer waiting, then invoke callbacks.
547+ function errorBuffer ( state , err ) {
548+ if ( state . writing || ! state . bufferedRequest ) {
549+ return ;
550+ }
551+
552+ for ( let entry = state . bufferedRequest ; entry ; entry = entry . next ) {
553+ const len = state . objectMode ? 1 : entry . chunk . length ;
554+ state . length -= len ;
555+ entry . callback ( err ) ;
556+ }
557+ state . bufferedRequest = null ;
558+ state . lastBufferedRequest = null ;
559+ state . bufferedRequestCount = 0 ;
560+ }
561+
537562// If there's something in the buffer waiting, then process it
538563function clearBuffer ( stream , state ) {
539564 state . bufferProcessing = true ;
@@ -820,12 +845,7 @@ const destroy = destroyImpl.destroy;
820845Writable . prototype . destroy = function ( err , cb ) {
821846 const state = this . _writableState ;
822847 if ( ! state . destroyed ) {
823- for ( let entry = state . bufferedRequest ; entry ; entry = entry . next ) {
824- process . nextTick ( entry . callback , new ERR_STREAM_DESTROYED ( 'write' ) ) ;
825- }
826- state . bufferedRequest = null ;
827- state . lastBufferedRequest = null ;
828- state . bufferedRequestCount = 0 ;
848+ process . nextTick ( errorBuffer , state , new ERR_STREAM_DESTROYED ( 'write' ) ) ;
829849 }
830850 destroy . call ( this , err , cb ) ;
831851 return this ;
0 commit comments