diff --git a/lib/internal/webstreams/adapters.js b/lib/internal/webstreams/adapters.js index 5768c71d21ff58..c907ba7db30268 100644 --- a/lib/internal/webstreams/adapters.js +++ b/lib/internal/webstreams/adapters.js @@ -8,6 +8,8 @@ const { Uint8Array, } = primordials; +const { TextEncoder } = require('internal/encoding'); + const { ReadableStream, isReadableStream, @@ -54,6 +56,7 @@ const { const { createDeferredPromise, kEmptyObject, + normalizeEncoding, } = require('internal/util'); const { @@ -73,6 +76,8 @@ const finished = require('internal/streams/end-of-stream'); const { UV_EOF } = internalBinding('uv'); +const encoder = new TextEncoder(); + /** * @typedef {import('../../stream').Writable} Writable * @typedef {import('../../stream').Readable} Readable @@ -255,11 +260,17 @@ function newStreamWritableFromWritableStream(writableStream, options = kEmptyObj write(chunk, encoding, callback) { if (typeof chunk === 'string' && decodeStrings && !objectMode) { - chunk = Buffer.from(chunk, encoding); - chunk = new Uint8Array( - chunk.buffer, - chunk.byteOffset, - chunk.byteLength); + const enc = normalizeEncoding(encoding); + + if (enc === 'utf8') { + chunk = encoder.encode(chunk); + } else { + chunk = Buffer.from(chunk, encoding); + chunk = new Uint8Array( + chunk.buffer, + chunk.byteOffset, + chunk.byteLength); + } } function done(error) { @@ -674,11 +685,17 @@ function newStreamDuplexFromReadableWritablePair(pair = kEmptyObject, options = write(chunk, encoding, callback) { if (typeof chunk === 'string' && decodeStrings && !objectMode) { - chunk = Buffer.from(chunk, encoding); - chunk = new Uint8Array( - chunk.buffer, - chunk.byteOffset, - chunk.byteLength); + const enc = normalizeEncoding(encoding); + + if (enc === 'utf8') { + chunk = encoder.encode(chunk); + } else { + chunk = Buffer.from(chunk, encoding); + chunk = new Uint8Array( + chunk.buffer, + chunk.byteOffset, + chunk.byteLength); + } } function done(error) {