diff --git a/lib/internal/webstreams/adapters.js b/lib/internal/webstreams/adapters.js index fc5ada12be3..443bea0386c 100644 --- a/lib/internal/webstreams/adapters.js +++ b/lib/internal/webstreams/adapters.js @@ -167,6 +167,24 @@ const noop = () => {}; // `failed`/`failure` latch a write that could not proceed. The callback // runs in the async context of the Node.js write that set it, as the // reaction to writer.write() did (see settle()). +/** + * Encodes a string chunk written to a Node.js Writable as a Uint8Array for a + * WritableStream. + * @param {string} chunk + * @param {string} encoding + * @returns {Uint8Array} + */ +function encodeStringChunk(chunk, encoding) { + if (normalizeEncoding(encoding) === 'utf8') + return encoder.encode(chunk); + const buffer = Buffer.from(chunk, encoding); + return new Uint8Array( + TypedArrayPrototypeGetBuffer(buffer), + TypedArrayPrototypeGetByteOffset(buffer), + TypedArrayPrototypeGetByteLength(buffer), + ); +} + function createWriteTracker(getDestination) { return { promise: null, @@ -493,20 +511,8 @@ function newStreamWritableFromWritableStream(writableStream, options = kEmptyObj }, write(chunk, encoding, callback) { - if (typeof chunk === 'string' && decodeStrings && !objectMode) { - const enc = normalizeEncoding(encoding); - - if (enc === 'utf8') { - chunk = encoder.encode(chunk); - } else { - chunk = Buffer.from(chunk, encoding); - chunk = new Uint8Array( - TypedArrayPrototypeGetBuffer(chunk), - TypedArrayPrototypeGetByteOffset(chunk), - TypedArrayPrototypeGetByteLength(chunk), - ); - } - } + if (typeof chunk === 'string' && decodeStrings && !objectMode) + chunk = encodeStringChunk(chunk, encoding); writeTracker.callback = callback; dispatchWrite(writer, chunk, writeTracker); @@ -948,20 +954,8 @@ function newStreamDuplexFromReadableWritablePair(pair = kEmptyObject, options = }, write(chunk, encoding, callback) { - if (typeof chunk === 'string' && decodeStrings && !objectMode) { - const enc = normalizeEncoding(encoding); - - if (enc === 'utf8') { - chunk = encoder.encode(chunk); - } else { - chunk = Buffer.from(chunk, encoding); - chunk = new Uint8Array( - TypedArrayPrototypeGetBuffer(chunk), - TypedArrayPrototypeGetByteOffset(chunk), - TypedArrayPrototypeGetByteLength(chunk), - ); - } - } + if (typeof chunk === 'string' && decodeStrings && !objectMode) + chunk = encodeStringChunk(chunk, encoding); writeTracker.callback = callback; dispatchWrite(writer, chunk, writeTracker);