From a0a0f721612e9c091b8c86825ec6efcb7a0e4f30 Mon Sep 17 00:00:00 2001 From: Robert Nagy Date: Tue, 7 Dec 2021 15:03:21 +0100 Subject: [PATCH] fix: readable.setEncoding Fixes: https://github.com/nodejs/undici/issues/1125#issuecomment-987724800 --- lib/api/readable.js | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/lib/api/readable.js b/lib/api/readable.js index b9768e29d8c..68b83d7132d 100644 --- a/lib/api/readable.js +++ b/lib/api/readable.js @@ -102,12 +102,12 @@ module.exports = class BodyReadable extends Readable { // https://fetch.spec.whatwg.org/#dom-body-text async text () { - return consume(this, 'text') + return toUSVString(await consume(this, 'string')) } // https://fetch.spec.whatwg.org/#dom-body-json async json () { - return consume(this, 'json') + return JSON.parse(await consume(this, 'string')) } // https://fetch.spec.whatwg.org/#dom-body-blob @@ -231,10 +231,12 @@ function consumeEnd (consume) { const { type, body, resolve, stream, length } = consume try { - if (type === 'text') { - resolve(toUSVString(Buffer.concat(body))) - } else if (type === 'json') { - resolve(JSON.parse(Buffer.concat(body))) + if (type === 'string') { + if (stream._readableState.decoder) { + resolve(body.join('')) + } else { + resolve(Buffer.concat(body).toString()) + } } else if (type === 'arrayBuffer') { const dst = new Uint8Array(length)