From afb84744c6071e77f0738a7ff1a52aaa81db8b77 Mon Sep 17 00:00:00 2001 From: Anna Henningsen Date: Tue, 28 May 2019 14:01:05 +0200 Subject: stream: convert existing buffer when calling .setEncoding Convert already-stored chunks when `.setEncoding()` is called so that subsequent `data` events will receive decoded strings, as they expect. Fixes: https://github.com/nodejs/node/issues/27932 PR-URL: https://github.com/nodejs/node/pull/27936 Reviewed-By: Matteo Collina Reviewed-By: Luigi Pinca Reviewed-By: Ruben Bridgewater Reviewed-By: Rich Trott --- lib/_stream_readable.js | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) (limited to 'lib/_stream_readable.js') diff --git a/lib/_stream_readable.js b/lib/_stream_readable.js index 5905c56bd4..163a042f08 100644 --- a/lib/_stream_readable.js +++ b/lib/_stream_readable.js @@ -321,9 +321,22 @@ Readable.prototype.isPaused = function() { Readable.prototype.setEncoding = function(enc) { if (!StringDecoder) StringDecoder = require('string_decoder').StringDecoder; - this._readableState.decoder = new StringDecoder(enc); + const decoder = new StringDecoder(enc); + this._readableState.decoder = decoder; // If setEncoding(null), decoder.encoding equals utf8 this._readableState.encoding = this._readableState.decoder.encoding; + + // Iterate over current buffer to convert already stored Buffers: + let p = this._readableState.buffer.head; + let content = ''; + while (p !== null) { + content += decoder.write(p.data); + p = p.next; + } + this._readableState.buffer.clear(); + if (content !== '') + this._readableState.buffer.push(content); + this._readableState.length = content.length; return this; }; -- cgit v1.2.3