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 1fa65164c70678..4328ef49f224d8 100644 --- a/test/parallel/test-whatwg-encoding-custom-textdecoder.js +++ b/test/parallel/test-whatwg-encoding-custom-textdecoder.js @@ -199,3 +199,10 @@ if (common.hasIntl) { const str = decoder.decode(chunk); assert.strictEqual(str, 'foo\ufffd'); } + +{ + const buffer = new ArrayBuffer(1); + new MessageChannel().port1.postMessage(buffer, [buffer]); // buffer is detached + const decoder = new TextDecoder(); + decoder.decode(buffer); +}