@@ -641,17 +641,20 @@ OutgoingMessage.prototype.write = function write(chunk, encoding, callback) {
641
641
return ret ;
642
642
} ;
643
643
644
+ function writeAfterEnd ( msg , callback ) {
645
+ const err = new ERR_STREAM_WRITE_AFTER_END ( ) ;
646
+ const triggerAsyncId = msg . socket ? msg . socket [ async_id_symbol ] : undefined ;
647
+ defaultTriggerAsyncIdScope ( triggerAsyncId ,
648
+ process . nextTick ,
649
+ writeAfterEndNT ,
650
+ msg ,
651
+ err ,
652
+ callback ) ;
653
+ }
654
+
644
655
function write_ ( msg , chunk , encoding , callback , fromEnd ) {
645
656
if ( msg . finished ) {
646
- const err = new ERR_STREAM_WRITE_AFTER_END ( ) ;
647
- const triggerAsyncId = msg . socket ? msg . socket [ async_id_symbol ] : undefined ;
648
- defaultTriggerAsyncIdScope ( triggerAsyncId ,
649
- process . nextTick ,
650
- writeAfterEndNT ,
651
- msg ,
652
- err ,
653
- callback ) ;
654
-
657
+ writeAfterEnd ( msg , callback ) ;
655
658
return true ;
656
659
}
657
660
@@ -748,17 +751,6 @@ OutgoingMessage.prototype.end = function end(chunk, encoding, callback) {
748
751
encoding = null ;
749
752
}
750
753
751
- if ( this . finished ) {
752
- if ( typeof callback === 'function' ) {
753
- if ( ! this . writableFinished ) {
754
- this . on ( 'finish' , callback ) ;
755
- } else {
756
- callback ( new ERR_STREAM_ALREADY_FINISHED ( 'end' ) ) ;
757
- }
758
- }
759
- return this ;
760
- }
761
-
762
754
if ( this . socket ) {
763
755
this . socket . cork ( ) ;
764
756
}
@@ -767,13 +759,28 @@ OutgoingMessage.prototype.end = function end(chunk, encoding, callback) {
767
759
if ( typeof chunk !== 'string' && ! ( chunk instanceof Buffer ) ) {
768
760
throw new ERR_INVALID_ARG_TYPE ( 'chunk' , [ 'string' , 'Buffer' ] , chunk ) ;
769
761
}
762
+
763
+ if ( this . finished ) {
764
+ writeAfterEnd ( this , callback ) ;
765
+ return this ;
766
+ }
767
+
770
768
if ( ! this . _header ) {
771
769
if ( typeof chunk === 'string' )
772
770
this . _contentLength = Buffer . byteLength ( chunk , encoding ) ;
773
771
else
774
772
this . _contentLength = chunk . length ;
775
773
}
776
774
write_ ( this , chunk , encoding , null , true ) ;
775
+ } else if ( this . finished ) {
776
+ if ( typeof callback === 'function' ) {
777
+ if ( ! this . writableFinished ) {
778
+ this . on ( 'finish' , callback ) ;
779
+ } else {
780
+ callback ( new ERR_STREAM_ALREADY_FINISHED ( 'end' ) ) ;
781
+ }
782
+ }
783
+ return this ;
777
784
} else if ( ! this . _header ) {
778
785
this . _contentLength = 0 ;
779
786
this . _implicitHeader ( ) ;
0 commit comments