diff --git a/lib/string_decoder.js b/lib/string_decoder.js index 7447bb3f4699b1..9eae594aaa27ea 100644 --- a/lib/string_decoder.js +++ b/lib/string_decoder.js @@ -43,6 +43,7 @@ const { const internalUtil = require('internal/util'); const { ERR_INVALID_ARG_TYPE, + ERR_INVALID_THIS, ERR_UNKNOWN_ENCODING } = require('internal/errors').codes; const isEncoding = Buffer[internalUtil.kIsEncodingSymbol]; @@ -101,6 +102,9 @@ StringDecoder.prototype.write = function write(buf) { throw new ERR_INVALID_ARG_TYPE('buf', ['Buffer', 'TypedArray', 'DataView'], buf); + if (!this[kNativeDecoder]) { + throw new ERR_INVALID_THIS('StringDecoder'); + } return decode(this[kNativeDecoder], buf); }; diff --git a/test/parallel/test-string-decoder.js b/test/parallel/test-string-decoder.js index be876f46e5af02..02f0a3a718bdec 100644 --- a/test/parallel/test-string-decoder.js +++ b/test/parallel/test-string-decoder.js @@ -210,6 +210,13 @@ if (common.enoughTestMem) { ); } +assert.throws( + () => new StringDecoder('utf8').__proto__.write(Buffer.from('abc')), // eslint-disable-line no-proto + { + code: 'ERR_INVALID_THIS', + } +); + // Test verifies that StringDecoder will correctly decode the given input // buffer with the given encoding to the expected output. It will attempt all // possible ways to write() the input buffer, see writeSequences(). The