Skip to content

Commit

Permalink
stream: simplify Writable.end()
Browse files Browse the repository at this point in the history
Simplifies Writable.end() by inlining and
de-duplicating code.

PR-URL: #32882
Reviewed-By: Anna Henningsen <[email protected]>
Reviewed-By: Luigi Pinca <[email protected]>
Reviewed-By: Gerhard Stöbich <[email protected]>
Reviewed-By: Ruben Bridgewater <[email protected]>
Reviewed-By: Matteo Collina <[email protected]>
  • Loading branch information
ronag authored and BethGriggs committed Apr 27, 2020
1 parent ccf6d3e commit 2ab4ebc
Showing 1 changed file with 13 additions and 20 deletions.
33 changes: 13 additions & 20 deletions lib/_stream_writable.js
Original file line number Diff line number Diff line change
Expand Up @@ -588,21 +588,26 @@ Writable.prototype.end = function(chunk, encoding, cb) {
this.uncork();
}

if (typeof cb !== 'function')
cb = nop;

// This is forgiving in terms of unnecessary calls to end() and can hide
// logic errors. However, usually such errors are harmless and causing a
// hard error can be disproportionately destructive. It is not always
// trivial for the user to determine whether end() needs to be called or not.
let err;
if (!state.errored && !state.ending) {
endWritable(this, state, cb);
state.ending = true;
finishMaybe(this, state, true);
state.ended = true;
} else if (state.finished) {
process.nextTick(cb, new ERR_STREAM_ALREADY_FINISHED('end'));
err = new ERR_STREAM_ALREADY_FINISHED('end');
} else if (state.destroyed) {
process.nextTick(cb, new ERR_STREAM_DESTROYED('end'));
} else if (cb !== nop) {
onFinished(this, state, cb);
err = new ERR_STREAM_DESTROYED('end');
}

if (typeof cb === 'function') {
if (err || state.finished)
process.nextTick(cb, err);
else
onFinished(this, state, cb);
}

return this;
Expand Down Expand Up @@ -683,18 +688,6 @@ function finish(stream, state) {
}
}

function endWritable(stream, state, cb) {
state.ending = true;
finishMaybe(stream, state, true);
if (cb !== nop) {
if (state.finished)
process.nextTick(cb);
else
onFinished(stream, state, cb);
}
state.ended = true;
}

function onCorkedFinish(corkReq, state, err) {
let entry = corkReq.entry;
corkReq.entry = null;
Expand Down

0 comments on commit 2ab4ebc

Please sign in to comment.