Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
stream: validate readable defaultEncoding
  • Loading branch information
marco-ippolito committed Jan 30, 2023
commit 998042a4acece1e0454ed574b239c00aee805090
10 changes: 9 additions & 1 deletion lib/internal/streams/readable.js
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand Down Expand Up @@ -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);
}
Comment thread
marco-ippolito marked this conversation as resolved.

// Ref the piped dest which we need a drain event on it
// type: null | Writable | Set<Writable>.
Expand Down
48 changes: 48 additions & 0 deletions test/parallel/test-stream-readable-default-encoding.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
'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');

const chunks = [];
r.on('data', (chunk) => chunks.push(chunk));
Comment thread
marco-ippolito marked this conversation as resolved.
Outdated

process.nextTick(common.mustCall(() => {
assert.strictEqual(Buffer.concat(chunks).toString('hex'), 'ab');
}), 1);

}

{
const r = new Readable({
read() {},
defaultEncoding: 'hex',
});

r.push('ab', 'utf-8');

const chunks = [];
r.on('data', (chunk) => chunks.push(chunk));

process.nextTick(common.mustCall(() => {
assert.strictEqual(Buffer.concat(chunks).toString('utf-8'), 'ab');
}), 1);
Comment thread
marco-ippolito marked this conversation as resolved.
Outdated
}