Files
scriptc/tests/corpus/5446-stream-buffer-chunks-dynamic.js
T
Chris Tate 712a82ae96 Hand stream chunks made from strings to user code as Buffers
Node converts a string chunk with Buffer.from(chunk, encoding) and
returns Buffer.concat for read(n), so every byte chunk user code
receives from a non-object-mode stream is a Buffer. The runtime made
these chunks as plain Uint8Array storage. A typed write(), transform()
or 'data' callback then printed String(chunk), `${chunk}` and
chunk + "" as comma-separated bytes (97,98) instead of the text, and
read(n) and read() after unshift(string) returned non-Buffer values to
untyped code.

The chunks the stream creates now carry the Buffer brand: write() and
push() of a string (with or without an encoding), transform output given
as a string (the callback or this.push), unshift() of a string, and the
concatenation read(n) returns.

Corpus 5445 (typed callbacks, pipeline and stream/promises pipeline)
and 5446 (untyped code, Buffer.isBuffer at each boundary) check this
against Node.
2026-10-14 21:55:39 -05:00

50 lines
1.2 KiB
JavaScript

// What a stream hands untyped code for string, Buffer and Uint8Array
// chunks: Buffers everywhere, including the concatenation read(n) returns
// and what read() returns after unshift() of a string.
import { PassThrough, Readable, Transform, Writable } from "node:stream";
const show = (where, c) => console.log(where, Buffer.isBuffer(c), c instanceof Uint8Array, String(c));
const w = new Writable({
write(c, enc, cb) {
show("write", c);
cb();
},
});
w.write("ab");
w.write(Buffer.from("cd"));
w.write(new Uint8Array([101, 102]));
w.end();
const r = new Readable({ read() {} });
r.on("data", (c) => show("data", c));
r.push("gh");
r.push(new Uint8Array([105, 106]));
r.push(null);
const t = new Transform({
transform(c, enc, cb) {
show("transform-in", c);
cb(null, String(c).toUpperCase());
},
});
t.on("data", (c) => show("transform-out", c));
t.write("kl");
t.end();
const p = new PassThrough();
p.on("data", (c) => show("passthrough", c));
p.write("mn");
p.end();
const rr = new Readable({ read() {} });
rr.push("op");
rr.push("qr");
rr.push(null);
rr.once("readable", () => {
const c = rr.read(3);
show("read(3)", c);
rr.unshift("z");
show("after-unshift", rr.read());
});