From c4aad946a5fbe2e7375690deeddd8e0e4cc9ad46 Mon Sep 17 00:00:00 2001 From: Robert Nagy Date: Mon, 16 Oct 2023 15:34:13 +0200 Subject: [PATCH] stream: refactor writable _write --- lib/internal/streams/writable.js | 28 +++++++++++++++++----------- 1 file changed, 17 insertions(+), 11 deletions(-) diff --git a/lib/internal/streams/writable.js b/lib/internal/streams/writable.js index b8f8b72ce8d113..84a802b67af744 100644 --- a/lib/internal/streams/writable.js +++ b/lib/internal/streams/writable.js @@ -443,21 +443,21 @@ Writable.prototype.pipe = function() { function _write(stream, chunk, encoding, cb) { const state = stream._writableState; - if (typeof encoding === 'function') { - cb = encoding; - encoding = (state[kState] & kDefaultUTF8Encoding) !== 0 ? 'utf8' : state.defaultEncoding; - } else { - 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 cb !== 'function') - cb = nop; + if (cb == null || typeof cb !== 'function') { + cb = nop; } 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); @@ -486,11 +486,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; };