stream: write should throw on unknown encoding

Validate encoding passed to write(chunk, encoding, cb) and
throw if it is invalid.

PR-URL: https://github.com/nodejs/node/pull/33075
Reviewed-By: James M Snell <jasnell@gmail.com>
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
This commit is contained in:
Robert Nagy
2020-04-26 11:16:43 +02:00
parent 563efb757e
commit 4bc7025309
2 changed files with 18 additions and 7 deletions

View File

@@ -268,6 +268,8 @@ Writable.prototype.write = function(chunk, encoding, cb) {
} else {
if (!encoding)
encoding = state.defaultEncoding;
else if (encoding !== 'buffer' && !Buffer.isEncoding(encoding))
throw new ERR_UNKNOWN_ENCODING(encoding);
if (typeof cb !== 'function')
cb = nop;
}

View File

@@ -4,17 +4,17 @@ const assert = require('assert');
const { Writable } = require('stream');
function expectError(w, arg, code, sync) {
function expectError(w, args, code, sync) {
if (sync) {
if (code) {
assert.throws(() => w.write(arg), { code });
assert.throws(() => w.write(...args), { code });
} else {
w.write(arg);
w.write(...args);
}
} else {
let errorCalled = false;
let ticked = false;
w.write(arg, common.mustCall((err) => {
w.write(...args, common.mustCall((err) => {
assert.strictEqual(ticked, true);
assert.strictEqual(errorCalled, false);
assert.strictEqual(err.code, code);
@@ -34,7 +34,7 @@ function test(autoDestroy) {
_write() {}
});
w.end();
expectError(w, 'asd', 'ERR_STREAM_WRITE_AFTER_END');
expectError(w, ['asd'], 'ERR_STREAM_WRITE_AFTER_END');
}
{
@@ -50,7 +50,7 @@ function test(autoDestroy) {
autoDestroy,
_write() {}
});
expectError(w, null, 'ERR_STREAM_NULL_VALUES', true);
expectError(w, [null], 'ERR_STREAM_NULL_VALUES', true);
}
{
@@ -58,7 +58,16 @@ function test(autoDestroy) {
autoDestroy,
_write() {}
});
expectError(w, {}, 'ERR_INVALID_ARG_TYPE', true);
expectError(w, [{}], 'ERR_INVALID_ARG_TYPE', true);
}
{
const w = new Writable({
decodeStrings: false,
autoDestroy,
_write() {}
});
expectError(w, ['asd', 'noencoding'], 'ERR_UNKNOWN_ENCODING', true);
}
}