Skip to content

Commit

Permalink
stream: refactor writable _write
Browse files Browse the repository at this point in the history
PR-URL: #50198
  • Loading branch information
ronag committed Oct 23, 2023
1 parent 8f742bb commit e9cf37a
Showing 1 changed file with 17 additions and 4 deletions.
21 changes: 17 additions & 4 deletions lib/internal/streams/writable.js
Original file line number Diff line number Diff line change
Expand Up @@ -443,9 +443,8 @@ Writable.prototype.pipe = function() {
function _write(stream, chunk, encoding, cb) {
const state = stream._writableState;

if (typeof encoding === 'function') {
cb = encoding;
encoding = null;
if (cb == null || typeof cb !== 'function') {
cb = nop;
}

if (!encoding)
Expand All @@ -458,7 +457,15 @@ function _write(stream, chunk, encoding, cb) {

if (chunk === null) {
throw new ERR_STREAM_NULL_VALUES();
} else if ((state[kState] & kObjectMode) === 0) {
}

if ((state[kState] & kObjectMode) === 0) {
if (!encoding) {
encoding = (state[kState] & kDefaultUTF8Encoding) !== 0 ? 'utf8' : state.defaultEncoding;
} else if (encoding !== 'buffer' && !Buffer.isEncoding(encoding)) {
throw new ERR_UNKNOWN_ENCODING(encoding);
}

if (typeof chunk === 'string') {
if ((state[kState] & kDecodeStrings) !== 0) {
chunk = Buffer.from(chunk, encoding);
Expand Down Expand Up @@ -487,11 +494,17 @@ function _write(stream, chunk, encoding, cb) {
errorOrDestroy(stream, err, true);
return err;
}

state.pendingcb++;
return writeOrBuffer(stream, state, chunk, encoding, cb);
}

Writable.prototype.write = function(chunk, encoding, cb) {
if (encoding != null && typeof encoding === 'function') {
cb = encoding;
encoding = null;
}

return _write(this, chunk, encoding, cb) === true;
};

Expand Down

0 comments on commit e9cf37a

Please sign in to comment.