Skip to content

Commit 63eca7f

Browse files
stream: validate readable defaultEncoding
PR-URL: #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>
1 parent 85f9b27 commit 63eca7f

File tree

2 files changed

+46
-1
lines changed

2 files changed

+46
-1
lines changed

lib/internal/streams/readable.js

+9-1
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,7 @@ const {
6565
ERR_OUT_OF_RANGE,
6666
ERR_STREAM_PUSH_AFTER_EOF,
6767
ERR_STREAM_UNSHIFT_AFTER_END_EVENT,
68+
ERR_UNKNOWN_ENCODING
6869
}
6970
} = require('internal/errors');
7071
const { validateObject } = require('internal/validators');
@@ -162,7 +163,14 @@ function ReadableState(options, stream, isDuplex) {
162163
// Crypto is kind of old and crusty. Historically, its default string
163164
// encoding is 'binary' so we have to make this configurable.
164165
// Everything else in the universe uses 'utf8', though.
165-
this.defaultEncoding = (options && options.defaultEncoding) || 'utf8';
166+
const defaultEncoding = options?.defaultEncoding;
167+
if (defaultEncoding == null) {
168+
this.defaultEncoding = 'utf8';
169+
} else if (Buffer.isEncoding(defaultEncoding)) {
170+
this.defaultEncoding = defaultEncoding;
171+
} else {
172+
throw new ERR_UNKNOWN_ENCODING(defaultEncoding);
173+
}
166174

167175
// Ref the piped dest which we need a drain event on it
168176
// type: null | Writable | Set<Writable>.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
'use strict';
2+
const common = require('../common');
3+
const assert = require('assert');
4+
const { Readable } = require('stream');
5+
6+
{
7+
assert.throws(() => {
8+
new Readable({
9+
read: () => {},
10+
defaultEncoding: 'my invalid encoding',
11+
});
12+
}, {
13+
code: 'ERR_UNKNOWN_ENCODING',
14+
});
15+
}
16+
17+
{
18+
const r = new Readable({
19+
read() {},
20+
defaultEncoding: 'hex'
21+
});
22+
23+
r.push('ab');
24+
25+
r.on('data', common.mustCall((chunk) => assert.strictEqual(chunk.toString('hex'), 'ab')), 1);
26+
}
27+
28+
{
29+
const r = new Readable({
30+
read() {},
31+
defaultEncoding: 'hex',
32+
});
33+
34+
r.push('xy', 'utf-8');
35+
36+
r.on('data', common.mustCall((chunk) => assert.strictEqual(chunk.toString('utf-8'), 'xy')), 1);
37+
}

0 commit comments

Comments
 (0)