diff --git a/lib/internal/encoding.js b/lib/internal/encoding.js index f9fa43228d5f57..0dec915124bf30 100644 --- a/lib/internal/encoding.js +++ b/lib/internal/encoding.js @@ -412,7 +412,13 @@ function makeTextDecoderICU() { decode(input = empty, options = kEmptyObject) { validateDecoder(this); if (isAnyArrayBuffer(input)) { - input = lazyBuffer().from(input); + try { + input = lazyBuffer().from(input); + } catch { + // If the buffer is detached, + // use an empty Uint8Array to avoid TypeError + input = empty; + } } else if (!isArrayBufferView(input)) { throw new ERR_INVALID_ARG_TYPE('input', ['ArrayBuffer', 'ArrayBufferView'], diff --git a/test/parallel/test-whatwg-encoding-custom-textdecoder.js b/test/parallel/test-whatwg-encoding-custom-textdecoder.js index fe08edc597d3f4..0274a1c4bf7768 100644 --- a/test/parallel/test-whatwg-encoding-custom-textdecoder.js +++ b/test/parallel/test-whatwg-encoding-custom-textdecoder.js @@ -206,3 +206,10 @@ if (common.hasIntl) { const str = decoder.decode(chunk); assert.strictEqual(str, '\ufffd'); } + +{ + const buffer = new ArrayBuffer(1); + new MessageChannel().port1.postMessage(buffer, [buffer]); // buffer is detached + const decoder = new TextDecoder(); + assert.strictEqual(decoder.decode(buffer), ''); +}