Skip to content

Commit dfe9ae2

Browse files
author
Henrik Blum
committed
fix: correct prePush ordering for ReadableString in object properties
When a ReadableString (created from a Readable stream) appeared as a non-first property in an object, _push() would prepend prePush (the opening quote) before the objectItem prefix (e.g. ',"key":'), producing invalid JSON like {"key":"value"","data":hello"}. Fix: separate the objectItem prefix from the data, so that prePush is inserted between the prefix and data rather than before the prefix. Before: '",key:value' — quote lands before comma After: ',key:"value' — quote lands after colon, before value Added two test cases covering ReadableStream values as non-first object properties.
1 parent 2910075 commit dfe9ae2

File tree

2 files changed

+17
-4
lines changed

2 files changed

+17
-4
lines changed

src/JsonStreamStringify.ts

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -454,12 +454,14 @@ export class JsonStreamStringify extends Readable {
454454
/** if set, this string will be prepended to the next _push call, if the call output is not empty, and set to undefined */
455455
prePush?: string;
456456
private _push(data) {
457-
const out = (this.objectItem ? this.objectItem.write() : '') + data;
458-
if (this.prePush && out.length) {
459-
this.buffer += this.prePush;
457+
const prefix = this.objectItem ? this.objectItem.write() : '';
458+
if (this.prePush && (prefix.length || data.length)) {
459+
this.buffer += prefix + this.prePush;
460460
this.prePush = undefined;
461+
} else {
462+
this.buffer += prefix;
461463
}
462-
this.buffer += out;
464+
this.buffer += data;
463465
if (this.buffer.length >= this.bufferSize) {
464466
this.pushCalled = !this.push(this.buffer);
465467
this.buffer = '';

test-src/JsonStreamStringify.spec.ts

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -274,6 +274,17 @@ describe('JsonStreamStringify', function () {
274274
a: readableStream(1, 2, 3),
275275
}, '{"a":[1,2,3]}'));
276276

277+
it('{key:"value",data:readableStream("hello")} should be {"key":"value","data":"hello"}', createTest({
278+
key: 'value',
279+
data: readableStream('hello'),
280+
}, '{"key":"value","data":"hello"}'));
281+
282+
it('{a:"b",c:readableStream("d"),e:"f"} should be {"a":"b","c":"d","e":"f"}', createTest({
283+
a: 'b',
284+
c: readableStream('d'),
285+
e: 'f',
286+
}, '{"a":"b","c":"d","e":"f"}'));
287+
277288
it('readableStream(\'a\', \'b\', \'c\') should be "abc"', createTest(readableStream('a', 'b', 'c'), '"abc"'));
278289

279290
it('readableStream(\'a\', \'b\', \'c\') should be "abc"', () => {

0 commit comments

Comments
 (0)