Skip to content

Commit 2ab4ebc

Browse files
ronagBethGriggs
authored andcommitted
stream: simplify Writable.end()
Simplifies Writable.end() by inlining and de-duplicating code. PR-URL: #32882 Reviewed-By: Anna Henningsen <anna@addaleax.net> Reviewed-By: Luigi Pinca <luigipinca@gmail.com> Reviewed-By: Gerhard Stöbich <deb2001-github@yahoo.de> Reviewed-By: Ruben Bridgewater <ruben@bridgewater.de> Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
1 parent ccf6d3e commit 2ab4ebc

File tree

1 file changed

+13
-20
lines changed

1 file changed

+13
-20
lines changed

lib/_stream_writable.js

+13-20
Original file line numberDiff line numberDiff line change
@@ -588,21 +588,26 @@ Writable.prototype.end = function(chunk, encoding, cb) {
588588
this.uncork();
589589
}
590590

591-
if (typeof cb !== 'function')
592-
cb = nop;
593-
594591
// This is forgiving in terms of unnecessary calls to end() and can hide
595592
// logic errors. However, usually such errors are harmless and causing a
596593
// hard error can be disproportionately destructive. It is not always
597594
// trivial for the user to determine whether end() needs to be called or not.
595+
let err;
598596
if (!state.errored && !state.ending) {
599-
endWritable(this, state, cb);
597+
state.ending = true;
598+
finishMaybe(this, state, true);
599+
state.ended = true;
600600
} else if (state.finished) {
601-
process.nextTick(cb, new ERR_STREAM_ALREADY_FINISHED('end'));
601+
err = new ERR_STREAM_ALREADY_FINISHED('end');
602602
} else if (state.destroyed) {
603-
process.nextTick(cb, new ERR_STREAM_DESTROYED('end'));
604-
} else if (cb !== nop) {
605-
onFinished(this, state, cb);
603+
err = new ERR_STREAM_DESTROYED('end');
604+
}
605+
606+
if (typeof cb === 'function') {
607+
if (err || state.finished)
608+
process.nextTick(cb, err);
609+
else
610+
onFinished(this, state, cb);
606611
}
607612

608613
return this;
@@ -683,18 +688,6 @@ function finish(stream, state) {
683688
}
684689
}
685690

686-
function endWritable(stream, state, cb) {
687-
state.ending = true;
688-
finishMaybe(stream, state, true);
689-
if (cb !== nop) {
690-
if (state.finished)
691-
process.nextTick(cb);
692-
else
693-
onFinished(stream, state, cb);
694-
}
695-
state.ended = true;
696-
}
697-
698691
function onCorkedFinish(corkReq, state, err) {
699692
let entry = corkReq.entry;
700693
corkReq.entry = null;

0 commit comments

Comments
 (0)