mirror of https://github.com/nodejs/node.git
stream: validate readable defaultEncoding
PR-URL: https://github.com/nodejs/node/pull/46430 Reviewed-By: Yagiz Nizipli <yagiz@nizipli.com> Reviewed-By: Paolo Insogna <paolo@cowtech.it> Reviewed-By: Matteo Collina <matteo.collina@gmail.com> Reviewed-By: Luigi Pinca <luigipinca@gmail.com> Reviewed-By: Benjamin Gruenbaum <benjamingr@gmail.com> Reviewed-By: Rafael Gonzaga <rafael.nunu@hotmail.com> Reviewed-By: Robert Nagy <ronagy@icloud.com>
This commit is contained in:
parent
85f9b27c14
commit
63eca7fec0
|
@ -65,6 +65,7 @@ const {
|
|||
ERR_OUT_OF_RANGE,
|
||||
ERR_STREAM_PUSH_AFTER_EOF,
|
||||
ERR_STREAM_UNSHIFT_AFTER_END_EVENT,
|
||||
ERR_UNKNOWN_ENCODING
|
||||
}
|
||||
} = require('internal/errors');
|
||||
const { validateObject } = require('internal/validators');
|
||||
|
@ -162,7 +163,14 @@ function ReadableState(options, stream, isDuplex) {
|
|||
// Crypto is kind of old and crusty. Historically, its default string
|
||||
// encoding is 'binary' so we have to make this configurable.
|
||||
// Everything else in the universe uses 'utf8', though.
|
||||
this.defaultEncoding = (options && options.defaultEncoding) || 'utf8';
|
||||
const defaultEncoding = options?.defaultEncoding;
|
||||
if (defaultEncoding == null) {
|
||||
this.defaultEncoding = 'utf8';
|
||||
} else if (Buffer.isEncoding(defaultEncoding)) {
|
||||
this.defaultEncoding = defaultEncoding;
|
||||
} else {
|
||||
throw new ERR_UNKNOWN_ENCODING(defaultEncoding);
|
||||
}
|
||||
|
||||
// Ref the piped dest which we need a drain event on it
|
||||
// type: null | Writable | Set<Writable>.
|
||||
|
|
|
@ -0,0 +1,37 @@
|
|||
'use strict';
|
||||
const common = require('../common');
|
||||
const assert = require('assert');
|
||||
const { Readable } = require('stream');
|
||||
|
||||
{
|
||||
assert.throws(() => {
|
||||
new Readable({
|
||||
read: () => {},
|
||||
defaultEncoding: 'my invalid encoding',
|
||||
});
|
||||
}, {
|
||||
code: 'ERR_UNKNOWN_ENCODING',
|
||||
});
|
||||
}
|
||||
|
||||
{
|
||||
const r = new Readable({
|
||||
read() {},
|
||||
defaultEncoding: 'hex'
|
||||
});
|
||||
|
||||
r.push('ab');
|
||||
|
||||
r.on('data', common.mustCall((chunk) => assert.strictEqual(chunk.toString('hex'), 'ab')), 1);
|
||||
}
|
||||
|
||||
{
|
||||
const r = new Readable({
|
||||
read() {},
|
||||
defaultEncoding: 'hex',
|
||||
});
|
||||
|
||||
r.push('xy', 'utf-8');
|
||||
|
||||
r.on('data', common.mustCall((chunk) => assert.strictEqual(chunk.toString('utf-8'), 'xy')), 1);
|
||||
}
|
Loading…
Reference in New Issue