Skip to content

Commit 9e7093f

Browse files
stream: validate writable defaultEncoding
PR-URL: #46322 Fixes: #46301 Reviewed-By: Robert Nagy <[email protected]> Reviewed-By: Matteo Collina <[email protected]> Reviewed-By: Paolo Insogna <[email protected]> Reviewed-By: Benjamin Gruenbaum <[email protected]> Reviewed-By: Yagiz Nizipli <[email protected]> Reviewed-By: Luigi Pinca <[email protected]>
1 parent a5fd53f commit 9e7093f

File tree

2 files changed

+55
-1
lines changed

2 files changed

+55
-1
lines changed

lib/internal/streams/writable.js

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -122,7 +122,14 @@ function WritableState(options, stream, isDuplex) {
122122
// Crypto is kind of old and crusty. Historically, its default string
123123
// encoding is 'binary' so we have to make this configurable.
124124
// Everything else in the universe uses 'utf8', though.
125-
this.defaultEncoding = (options && options.defaultEncoding) || 'utf8';
125+
const defaultEncoding = options?.defaultEncoding;
126+
if (defaultEncoding == null) {
127+
this.defaultEncoding = 'utf8';
128+
} else if (Buffer.isEncoding(defaultEncoding)) {
129+
this.defaultEncoding = defaultEncoding;
130+
} else {
131+
throw new ERR_UNKNOWN_ENCODING(defaultEncoding);
132+
}
126133

127134
// Not an actual buffer we keep track of, but a measurement
128135
// of how much we're waiting to get pushed to some underlying

test/parallel/test-stream-writable-decoded-encoding.js

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,3 +56,50 @@ class MyWritable extends stream.Writable {
5656
m.write('some-text', 'utf8');
5757
m.end();
5858
}
59+
60+
{
61+
assert.throws(() => {
62+
const m = new MyWritable(null, {
63+
defaultEncoding: 'my invalid encoding',
64+
});
65+
m.end();
66+
}, {
67+
code: 'ERR_UNKNOWN_ENCODING',
68+
});
69+
}
70+
71+
{
72+
const w = new MyWritable(function(isBuffer, type, enc) {
73+
assert(!isBuffer);
74+
assert.strictEqual(type, 'string');
75+
assert.strictEqual(enc, 'hex');
76+
}, {
77+
defaultEncoding: 'hex',
78+
decodeStrings: false
79+
});
80+
w.write('asd');
81+
w.end();
82+
}
83+
84+
{
85+
const w = new MyWritable(function(isBuffer, type, enc) {
86+
assert(!isBuffer);
87+
assert.strictEqual(type, 'string');
88+
assert.strictEqual(enc, 'utf8');
89+
}, {
90+
defaultEncoding: null,
91+
decodeStrings: false
92+
});
93+
w.write('asd');
94+
w.end();
95+
}
96+
97+
{
98+
const m = new MyWritable(function(isBuffer, type, enc) {
99+
assert.strictEqual(type, 'object');
100+
assert.strictEqual(enc, 'utf8');
101+
}, { defaultEncoding: 'hex',
102+
objectMode: true });
103+
m.write({ foo: 'bar' }, 'utf8');
104+
m.end();
105+
}

0 commit comments

Comments
 (0)