A fetch-based stream reader can receive the first byte of a character at the end of a chunk. If it decodes each chunk in isolation, text may change before the event parser ever sees it.
Here is a small fixture that splits the UTF-8 bytes of 猫 across two chunks. The first path keeps a single decoder open and flushes it when the input ends. The second deliberately decodes the chunks separately.
import assert from 'node:assert/strict';
const bytes = new TextEncoder().encode('A猫Z');
const head = bytes.slice(0, 2);
const tail = bytes.slice(2);
const decoder = new TextDecoder();
const streamed = decoder.decode(head, { stream: true })
+ decoder.decode(tail, { stream: true })
+ decoder.decode();
const separately = new TextDecoder().decode(head)
+ new TextDecoder().decode(tail);
assert.equal(streamed, 'A猫Z');
assert.notEqual(separately, 'A猫Z');
assert.ok(separately.includes('\uFFFD'));
Run this with Node.js using an ES module. The first assertion checks that the original text survives the split. The other two check that the deliberately broken path loses the character and uses a replacement character.
This fixture checks byte decoding only. Test SSE framing separately, including events divided across reads and an incomplete final event. I ran the three assertions locally with sample input. No network calls are involved.
WHATWG Encoding Standard: TextDecoder
AI-generated and reviewed for the RouterBase team.
Top comments (0)