From f87921de3b1cbd10cbf2bbe281d83d09025ced2d Mon Sep 17 00:00:00 2001 From: Robert Nagy Date: Tue, 24 Oct 2023 15:45:23 +0200 Subject: [PATCH] stream: refactor writable _write PR-URL: https://github.com/nodejs/node/pull/50198 Reviewed-By: Yagiz Nizipli Reviewed-By: Marco Ippolito Reviewed-By: Matteo Collina --- lib/internal/streams/writable.js | 29 +++++++++++++++---------- test/parallel/test-stream-uint8array.js | 2 +- 2 files changed, 18 insertions(+), 13 deletions(-) diff --git a/lib/internal/streams/writable.js b/lib/internal/streams/writable.js index 8bf967e556bf80..ae860f8c8f00f7 100644 --- a/lib/internal/streams/writable.js +++ b/lib/internal/streams/writable.js @@ -443,22 +443,21 @@ Writable.prototype.pipe = function() { function _write(stream, chunk, encoding, cb) { const state = stream._writableState; - if (typeof encoding === 'function') { - cb = encoding; - encoding = null; - } - - if (!encoding) - encoding = (state[kState] & kDefaultUTF8Encoding) !== 0 ? 'utf8' : state[kDefaultEncodingValue]; - else if (encoding !== 'buffer' && !Buffer.isEncoding(encoding)) - throw new ERR_UNKNOWN_ENCODING(encoding); - - if (cb == null || typeof cb !== 'function') + 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); @@ -487,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; }; diff --git a/test/parallel/test-stream-uint8array.js b/test/parallel/test-stream-uint8array.js index 38a45d54048967..f1de4c873fd3a8 100644 --- a/test/parallel/test-stream-uint8array.js +++ b/test/parallel/test-stream-uint8array.js @@ -38,7 +38,7 @@ const GHI = new Uint8Array([0x47, 0x48, 0x49]); assert(!(chunk instanceof Buffer)); assert(chunk instanceof Uint8Array); assert.strictEqual(chunk, ABC); - assert.strictEqual(encoding, 'utf8'); + assert.strictEqual(encoding, undefined); cb(); }) });