mirror of
https://github.com/zebrajr/node.git
synced 2026-01-15 12:15:26 +00:00
Add support for the creation of ReadableByteStream to Readable.toWeb()
and Duplex.toWeb()
This enables the use of .getReader({ mode: "byob" }) on
e.g. socket().toWeb()
Refs: https://github.com/nodejs/node/issues/56004#issuecomment-2908265316
Refs: https://developer.mozilla.org/en-US/docs/Web/API/Streams_API/Using_readable_byte_streams
PR-URL: https://github.com/nodejs/node/pull/58664
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: Ethan Arrowood <ethan@arrowood.dev>
Reviewed-By: Mattias Buelens <mattias@buelens.com>
Reviewed-By: James M Snell <jasnell@gmail.com>
50 lines
1.2 KiB
JavaScript
50 lines
1.2 KiB
JavaScript
'use strict';
|
|
require('../common');
|
|
const { Readable } = require('stream');
|
|
const assert = require('assert');
|
|
const common = require('../common');
|
|
|
|
let count = 0;
|
|
|
|
const nodeStream = new Readable({
|
|
read(size) {
|
|
if (this.destroyed) {
|
|
return;
|
|
}
|
|
// Simulate a stream that pushes sequences of 16 bytes
|
|
const buffer = Buffer.alloc(size);
|
|
for (let i = 0; i < size; i++) {
|
|
buffer[i] = count++ % 16;
|
|
}
|
|
this.push(buffer);
|
|
}
|
|
});
|
|
|
|
// Test validation of 'type' option
|
|
assert.throws(
|
|
() => {
|
|
Readable.toWeb(nodeStream, { type: 'wrong type' });
|
|
},
|
|
{
|
|
code: 'ERR_INVALID_ARG_VALUE'
|
|
}
|
|
);
|
|
|
|
// Test normal operation with ReadableByteStream
|
|
const webStream = Readable.toWeb(nodeStream, { type: 'bytes' });
|
|
const reader = webStream.getReader({ mode: 'byob' });
|
|
const expected = new Uint8Array(16);
|
|
for (let i = 0; i < 16; i++) {
|
|
expected[i] = count++;
|
|
}
|
|
|
|
for (let i = 0; i < 1000; i++) {
|
|
// Read 16 bytes of data from the stream
|
|
const receive = new Uint8Array(16);
|
|
reader.read(receive).then(common.mustCall((result) => {
|
|
// Verify the data received
|
|
assert.ok(!result.done);
|
|
assert.deepStrictEqual(result.value, expected);
|
|
}));
|
|
}
|