Commit baf98fa

Browse files
jasnelladuh95
authored andcommitted
stream: add stream/iter to classic stream adapters
Signed-off-by: James M Snell <jasnell@gmail.com> Assisted-by: Opencode/Opus 4.6 PR-URL: #62469 Backport-PR-URL: #64675 Reviewed-By: Robert Nagy <ronagy@icloud.com>
1 parent a290f51 commit baf98fa

17 files changed

Lines changed: 3848 additions & 14 deletions

‎doc/api/errors.md‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2906,6 +2906,13 @@ An attempt was made to call [`stream.pipe()`][] on a [`Writable`][] stream.
29062906
A stream method was called that cannot complete because the stream was
29072907
destroyed using `stream.destroy()`.
29082908

2909+
<aid="ERR_STREAM_ITER_MISSING_FLAG"></a>
2910+
2911+
### `ERR_STREAM_ITER_MISSING_FLAG`
2912+
2913+
A stream/iter API was used without the `--experimental-stream-iter` CLI flag
2914+
enabled.
2915+
29092916
<aid="ERR_STREAM_NULL_VALUES"></a>
29102917

29112918
### `ERR_STREAM_NULL_VALUES`

‎doc/api/stream.md‎

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1998,6 +1998,61 @@ option. In the code example above, data will be in a single chunk if the file
19981998
has less then 64 KiB of data because no `highWaterMark` option is provided to
19991999
[`fs.createReadStream()`][].
20002000

2001+
##### `readable[Symbol.for('Stream.toAsyncStreamable')]()`
2002+
2003+
<!-- YAML
2004+
added: REPLACEME
2005+
-->
2006+
2007+
> Stability: 1 - Experimental
2008+
2009+
* Returns: {AsyncIterable} An `AsyncIterable<Uint8Array[]>` that yields
2010+
batched chunks from the stream.
2011+
2012+
When the `--experimental-stream-iter` flag is enabled, `Readable` streams
2013+
implement the [`Stream.toAsyncStreamable`][] protocol, enabling efficient
2014+
consumption by the [`stream/iter`][] API.
2015+
2016+
This provides a batched async iterator that drains the stream's internal
2017+
buffer into `Uint8Array[]` batches, amortizing the per-chunk Promise overhead
2018+
of the standard `Symbol.asyncIterator` path. For byte-mode streams, chunks
2019+
are yielded directly as `Buffer` instances (which are `Uint8Array` subclasses).
2020+
For object-mode or encoded streams, each chunk is normalized to `Uint8Array`
2021+
before batching.
2022+
2023+
The returned iterator is tagged as a validated source, so [`from()`][stream-iter-from]
2024+
passes it through without additional normalization.
2025+
2026+
```mjs
2027+
import { Readable } from'node:stream';
2028+
import { text, from } from'node:stream/iter';
2029+
2030+
constreadable=newReadable({
2031+
read() { this.push('hello'); this.push(null); },
2032+
});
2033+
2034+
// Readable is automatically consumed via toAsyncStreamable
2035+
console.log(awaittext(from(readable))); // 'hello'
2036+
```
2037+
2038+
```cjs
2039+
const { Readable } =require('node:stream');
2040+
const { text, from } =require('node:stream/iter');
2041+
2042+
asyncfunctionrun() {
2043+
constreadable=newReadable({
2044+
read() { this.push('hello'); this.push(null); },
2045+
});
2046+
2047+
console.log(awaittext(from(readable))); // 'hello'
2048+
}
2049+
2050+
run().catch(console.error);
2051+
```
2052+
2053+
Without the `--experimental-stream-iter` flag, calling this method throws
2054+
[`ERR_STREAM_ITER_MISSING_FLAG`][].
2055+
20012056
##### `readable[Symbol.asyncDispose]()`
20022057

20032058
<!-- YAML
@@ -4974,8 +5029,10 @@ contain multi-byte characters.
49745029
[`'finish'`]: #event-finish
49755030
[`'readable'`]: #event-readable
49765031
[`Duplex`]: #class-streamduplex
5032+
[`ERR_STREAM_ITER_MISSING_FLAG`]: errors.md#err_stream_iter_missing_flag
49775033
[`EventEmitter`]: events.md#class-eventemitter
49785034
[`Readable`]: #class-streamreadable
5035+
[`Stream.toAsyncStreamable`]: stream_iter.md#streamtoasyncstreamable
49795036
[`Symbol.hasInstance`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/hasInstance
49805037
[`Transform`]: #class-streamtransform
49815038
[`Writable`]: #class-streamwritable
@@ -5001,6 +5058,7 @@ contain multi-byte characters.
50015058
[`stream.uncork()`]: #writableuncork
50025059
[`stream.unpipe()`]: #readableunpipedestination
50035060
[`stream.wrap()`]: #readablewrapstream
5061+
[`stream/iter`]: stream_iter.md
50045062
[`writable._final()`]: #writable_finalcallback
50055063
[`writable._write()`]: #writable_writechunk-encoding-callback
50065064
[`writable._writev()`]: #writable_writevchunks-callback
@@ -5029,6 +5087,7 @@ contain multi-byte characters.
50295087
[stream-end]: #writableendchunk-encoding-callback
50305088
[stream-finished]: #streamfinishedstream-options-callback
50315089
[stream-finished-promise]: #streamfinishedstream-options
5090+
[stream-iter-from]: stream_iter.md#frominput
50325091
[stream-pause]: #readablepause
50335092
[stream-pipeline]: #streampipelinesource-transforms-destination-callback
50345093
[stream-pipeline-promise]: #streampipelinesource-transforms-destination-options

‎doc/api/stream_iter.md‎

Lines changed: 257 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1424,6 +1424,258 @@ Compression and decompression transforms for use with `pull()`, `pullSync()`,
14241424
`pipeTo()`, and `pipeToSync()` are available via the [`node:zlib/iter`][]
14251425
module. See the [`node:zlib/iter` documentation][] for details.
14261426

1427+
## Classic stream interop
1428+
1429+
These utility functions bridge between classic
1430+
[`stream.Readable`][]/[`stream.Writable`][] streams and the `stream/iter`
1431+
API.
1432+
1433+
Both `fromReadable()` and `fromWritable()` accept duck-typed objects -- they
1434+
do not require the input to extend `stream.Readable` or `stream.Writable`
1435+
directly. The minimum contract is described below for each function.
1436+
1437+
### `fromReadable(readable)`
1438+
1439+
<!-- YAML
1440+
added: REPLACEME
1441+
-->
1442+
1443+
> Stability: 1 - Experimental
1444+
1445+
*`readable` {stream.Readable|Object} A classic Readable stream or any object
1446+
with `read()` and `on()` methods.
1447+
* Returns: {AsyncIterable\<Uint8Array\[]>} A stream/iter async iterable source.
1448+
1449+
Converts a classic Readable stream (or duck-typed equivalent) into a
1450+
stream/iter async iterable source that can be passed to [`from()`][],
1451+
[`pull()`][], [`text()`][], etc.
1452+
1453+
If the object implements the [`toAsyncStreamable`][] protocol (as
1454+
`stream.Readable` does), that protocol is used. Otherwise, the function
1455+
duck-types on `read()` and `on()` (EventEmitter) and wraps the stream with
1456+
a batched async iterator.
1457+
1458+
The result is cached per instance -- calling `fromReadable()` twice with the
1459+
same stream returns the same iterable.
1460+
1461+
For object-mode or encoded Readable streams, chunks are automatically
1462+
normalized to `Uint8Array`.
1463+
1464+
```mjs
1465+
import { Readable } from'node:stream';
1466+
import { fromReadable, text } from'node:stream/iter';
1467+
1468+
constreadable=newReadable({
1469+
read() { this.push('hello world'); this.push(null); },
1470+
});
1471+
1472+
constresult=awaittext(fromReadable(readable));
1473+
console.log(result); // 'hello world'
1474+
```
1475+
1476+
```cjs
1477+
const { Readable } =require('node:stream');
1478+
const { fromReadable, text } =require('node:stream/iter');
1479+
1480+
constreadable=newReadable({
1481+
read() { this.push('hello world'); this.push(null); },
1482+
});
1483+
1484+
asyncfunctionrun() {
1485+
constresult=awaittext(fromReadable(readable));
1486+
console.log(result); // 'hello world'
1487+
}
1488+
run();
1489+
```
1490+
1491+
### `fromWritable(writable[, options])`
1492+
1493+
<!-- YAML
1494+
added: REPLACEME
1495+
-->
1496+
1497+
> Stability: 1 - Experimental
1498+
1499+
*`writable` {stream.Writable|Object} A classic Writable stream or any object
1500+
with `write()` and `on()` methods.
1501+
*`options` {Object}
1502+
*`backpressure` {string} Backpressure policy. **Default:**`'strict'`.
1503+
*`'strict'` -- writes are rejected when the buffer is full. Catches
1504+
callers that ignore backpressure.
1505+
*`'block'` -- writes wait for drain when the buffer is full. Recommended
1506+
for use with [`pipeTo()`][].
1507+
*`'drop-newest'` -- writes are silently discarded when the buffer is full.
1508+
*`'drop-oldest'` -- **not supported**. Throws `ERR_INVALID_ARG_VALUE`.
1509+
* Returns: {Object} A stream/iter Writer adapter.
1510+
1511+
Creates a stream/iter Writer adapter from a classic Writable stream (or
1512+
duck-typed equivalent). The adapter can be passed to [`pipeTo()`][] as a
1513+
destination.
1514+
1515+
Since all writes on a classic Writable are fundamentally asynchronous,
1516+
the synchronous Writer methods (`writeSync`, `writevSync`, `endSync`) always
1517+
return `false` or `-1`, deferring to the async path. The per-write
1518+
`options.signal` parameter from the Writer interface is also ignored.
1519+
1520+
The result is cached per instance -- calling `fromWritable()` twice with the
1521+
same stream returns the same Writer.
1522+
1523+
For duck-typed streams that do not expose `writableHighWaterMark`,
1524+
`writableLength`, or similar properties, sensible defaults are used.
1525+
Object-mode writables (if detectable) are rejected since the Writer
1526+
interface is bytes-only.
1527+
1528+
```mjs
1529+
import { Writable } from'node:stream';
1530+
import { from, fromWritable, pipeTo } from'node:stream/iter';
1531+
1532+
constwritable=newWritable({
1533+
write(chunk, encoding, cb) { console.log(chunk.toString()); cb(); },
1534+
});
1535+
1536+
awaitpipeTo(from('hello world'),
1537+
fromWritable(writable, { backpressure:'block' }));
1538+
```
1539+
1540+
```cjs
1541+
const { Writable } =require('node:stream');
1542+
const { from, fromWritable, pipeTo } =require('node:stream/iter');
1543+
1544+
asyncfunctionrun() {
1545+
constwritable=newWritable({
1546+
write(chunk, encoding, cb) { console.log(chunk.toString()); cb(); },
1547+
});
1548+
1549+
awaitpipeTo(from('hello world'),
1550+
fromWritable(writable, { backpressure:'block' }));
1551+
}
1552+
run();
1553+
```
1554+
1555+
### `toReadable(source[, options])`
1556+
1557+
<!-- YAML
1558+
added: REPLACEME
1559+
-->
1560+
1561+
> Stability: 1 - Experimental
1562+
1563+
*`source` {AsyncIterable} An `AsyncIterable<Uint8Array[]>` source, such as
1564+
the return value of [`pull()`][] or [`from()`][].
1565+
*`options` {Object}
1566+
*`highWaterMark` {number} The internal buffer size in bytes before
1567+
backpressure is applied. **Default:**`65536` (64 KB).
1568+
*`signal` {AbortSignal} An optional signal to abort the readable.
1569+
* Returns: {stream.Readable}
1570+
1571+
Creates a byte-mode [`stream.Readable`][] from an `AsyncIterable<Uint8Array[]>`
1572+
(the native batch format used by the stream/iter API). Each `Uint8Array` in a
1573+
yielded batch is pushed as a separate chunk into the Readable.
1574+
1575+
```mjs
1576+
import { createWriteStream } from'node:fs';
1577+
import { from, pull, toReadable } from'node:stream/iter';
1578+
import { compressGzip } from'node:zlib/iter';
1579+
1580+
constsource=pull(from('hello world'), compressGzip());
1581+
constreadable=toReadable(source);
1582+
1583+
readable.pipe(createWriteStream('output.gz'));
1584+
```
1585+
1586+
```cjs
1587+
const { createWriteStream } =require('node:fs');
1588+
const { from, pull, toReadable } =require('node:stream/iter');
1589+
const { compressGzip } =require('node:zlib/iter');
1590+
1591+
constsource=pull(from('hello world'), compressGzip());
1592+
constreadable=toReadable(source);
1593+
1594+
readable.pipe(createWriteStream('output.gz'));
1595+
```
1596+
1597+
### `toReadableSync(source[, options])`
1598+
1599+
<!-- YAML
1600+
added: REPLACEME
1601+
-->
1602+
1603+
> Stability: 1 - Experimental
1604+
1605+
*`source` {Iterable} An `Iterable<Uint8Array[]>` source, such as the
1606+
return value of [`pullSync()`][] or [`fromSync()`][].
1607+
*`options` {Object}
1608+
*`highWaterMark` {number} The internal buffer size in bytes before
1609+
backpressure is applied. **Default:**`65536` (64 KB).
1610+
* Returns: {stream.Readable}
1611+
1612+
Creates a byte-mode [`stream.Readable`][] from a synchronous
1613+
`Iterable<Uint8Array[]>`. The `_read()` method pulls from the iterator
1614+
synchronously, so data is available immediately via `readable.read()`.
1615+
1616+
```mjs
1617+
import { fromSync, toReadableSync } from'node:stream/iter';
1618+
1619+
constsource=fromSync('hello world');
1620+
constreadable=toReadableSync(source);
1621+
1622+
console.log(readable.read().toString()); // 'hello world'
1623+
```
1624+
1625+
```cjs
1626+
const { fromSync, toReadableSync } =require('node:stream/iter');
1627+
1628+
constsource=fromSync('hello world');
1629+
constreadable=toReadableSync(source);
1630+
1631+
console.log(readable.read().toString()); // 'hello world'
1632+
```
1633+
1634+
### `toWritable(writer)`
1635+
1636+
<!-- YAML
1637+
added: REPLACEME
1638+
-->
1639+
1640+
> Stability: 1 - Experimental
1641+
1642+
*`writer` {Object} A stream/iter Writer. Only the `write()` method is
1643+
required; `end()`, `fail()`, `writeSync()`, `writevSync()`, `endSync()`,
1644+
and `writev()` are optional.
1645+
* Returns: {stream.Writable}
1646+
1647+
Creates a classic [`stream.Writable`][] backed by a stream/iter Writer.
1648+
1649+
Each `_write()` / `_writev()` call attempts the Writer's synchronous method
1650+
first (`writeSync` / `writevSync`), falling back to the async method if the
1651+
sync path returns `false` or throws. Similarly, `_final()` tries `endSync()`
1652+
before `end()`. When the sync path succeeds, the callback is deferred via
1653+
`queueMicrotask` to preserve the async resolution contract.
1654+
1655+
The Writable's `highWaterMark` is set to `Number.MAX_SAFE_INTEGER` to
1656+
effectively disable its internal buffering, allowing the underlying Writer
1657+
to manage backpressure directly.
1658+
1659+
```mjs
1660+
import { push, toWritable } from'node:stream/iter';
1661+
1662+
const { writer, readable } =push();
1663+
constwritable=toWritable(writer);
1664+
1665+
writable.write('hello');
1666+
writable.end();
1667+
```
1668+
1669+
```cjs
1670+
const { push, toWritable } =require('node:stream/iter');
1671+
1672+
const { writer, readable } =push();
1673+
constwritable=toWritable(writer);
1674+
1675+
writable.write('hello');
1676+
writable.end();
1677+
```
1678+
14271679
## Protocol symbols
14281680

14291681
These well-known symbols allow third-party objects to participate in the
@@ -1816,10 +2068,15 @@ console.log(textSync(stream)); // 'hello world'
18162068
[`arrayBuffer()`]: #arraybuffersource-options
18172069
[`bytes()`]: #bytessource-options
18182070
[`from()`]: #frominput
2071+
[`fromSync()`]: #fromsyncinput
18192072
[`node:zlib/iter`]: zlib_iter.md
18202073
[`node:zlib/iter` documentation]: zlib_iter.md
18212074
[`pipeTo()`]: #pipetosource-transforms-writer-options
18222075
[`pull()`]: #pullsource-transforms-options
2076+
[`pullSync()`]: #pullsyncsource-transforms-options
18232077
[`share()`]: #sharesource-options
2078+
[`stream.Readable`]: stream.md#class-streamreadable
2079+
[`stream.Writable`]: stream.md#class-streamwritable
18242080
[`tap()`]: #tapcallback
18252081
[`text()`]: #textsource-options
2082+
[`toAsyncStreamable`]: #streamtoasyncstreamable

‎lib/internal/errors.js‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1775,6 +1775,8 @@ E('ERR_STREAM_ALREADY_FINISHED',
17751775
Error);
17761776
E('ERR_STREAM_CANNOT_PIPE','Cannot pipe, not readable',Error);
17771777
E('ERR_STREAM_DESTROYED','Cannot call %s after a stream was destroyed',Error);
1778+
E('ERR_STREAM_ITER_MISSING_FLAG',
1779+
'The stream/iter API requires the --experimental-stream-iter flag',TypeError);
17781780
E('ERR_STREAM_NULL_VALUES','May not write null values to stream',TypeError);
17791781
E('ERR_STREAM_PREMATURE_CLOSE','Premature close',Error);
17801782
E('ERR_STREAM_PUSH_AFTER_EOF','stream.push() after EOF',Error);

0 commit comments

Comments
 (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content

Commit baf98fa

Browse files
jasnelladuh95
authored andcommitted
stream: add stream/iter to classic stream adapters
Signed-off-by: James M Snell <jasnell@gmail.com> Assisted-by: Opencode/Opus 4.6 PR-URL: #62469 Backport-PR-URL: #64675 Reviewed-By: Robert Nagy <ronagy@icloud.com>
1 parent a290f51 commit baf98fa

17 files changed

Lines changed: 3848 additions & 14 deletions

‎doc/api/errors.md‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2906,6 +2906,13 @@ An attempt was made to call [`stream.pipe()`][] on a [`Writable`][] stream.
29062906
A stream method was called that cannot complete because the stream was
29072907
destroyed using `stream.destroy()`.
29082908

2909+
<aid="ERR_STREAM_ITER_MISSING_FLAG"></a>
2910+
2911+
### `ERR_STREAM_ITER_MISSING_FLAG`
2912+
2913+
A stream/iter API was used without the `--experimental-stream-iter` CLI flag
2914+
enabled.
2915+
29092916
<aid="ERR_STREAM_NULL_VALUES"></a>
29102917

29112918
### `ERR_STREAM_NULL_VALUES`

‎doc/api/stream.md‎

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1998,6 +1998,61 @@ option. In the code example above, data will be in a single chunk if the file
19981998
has less then 64 KiB of data because no `highWaterMark` option is provided to
19991999
[`fs.createReadStream()`][].
20002000

2001+
##### `readable[Symbol.for('Stream.toAsyncStreamable')]()`
2002+
2003+
<!-- YAML
2004+
added: REPLACEME
2005+
-->
2006+
2007+
> Stability: 1 - Experimental
2008+
2009+
* Returns: {AsyncIterable} An `AsyncIterable<Uint8Array[]>` that yields
2010+
batched chunks from the stream.
2011+
2012+
When the `--experimental-stream-iter` flag is enabled, `Readable` streams
2013+
implement the [`Stream.toAsyncStreamable`][] protocol, enabling efficient
2014+
consumption by the [`stream/iter`][] API.
2015+
2016+
This provides a batched async iterator that drains the stream's internal
2017+
buffer into `Uint8Array[]` batches, amortizing the per-chunk Promise overhead
2018+
of the standard `Symbol.asyncIterator` path. For byte-mode streams, chunks
2019+
are yielded directly as `Buffer` instances (which are `Uint8Array` subclasses).
2020+
For object-mode or encoded streams, each chunk is normalized to `Uint8Array`
2021+
before batching.
2022+
2023+
The returned iterator is tagged as a validated source, so [`from()`][stream-iter-from]
2024+
passes it through without additional normalization.
2025+
2026+
```mjs
2027+
import { Readable } from'node:stream';
2028+
import { text, from } from'node:stream/iter';
2029+
2030+
constreadable=newReadable({
2031+
read() { this.push('hello'); this.push(null); },
2032+
});
2033+
2034+
// Readable is automatically consumed via toAsyncStreamable
2035+
console.log(awaittext(from(readable))); // 'hello'
2036+
```
2037+
2038+
```cjs
2039+
const { Readable } =require('node:stream');
2040+
const { text, from } =require('node:stream/iter');
2041+
2042+
asyncfunctionrun() {
2043+
constreadable=newReadable({
2044+
read() { this.push('hello'); this.push(null); },
2045+
});
2046+
2047+
console.log(awaittext(from(readable))); // 'hello'
2048+
}
2049+
2050+
run().catch(console.error);
2051+
```
2052+
2053+
Without the `--experimental-stream-iter` flag, calling this method throws
2054+
[`ERR_STREAM_ITER_MISSING_FLAG`][].
2055+
20012056
##### `readable[Symbol.asyncDispose]()`
20022057

20032058
<!-- YAML
@@ -4974,8 +5029,10 @@ contain multi-byte characters.
49745029
[`'finish'`]: #event-finish
49755030
[`'readable'`]: #event-readable
49765031
[`Duplex`]: #class-streamduplex
5032+
[`ERR_STREAM_ITER_MISSING_FLAG`]: errors.md#err_stream_iter_missing_flag
49775033
[`EventEmitter`]: events.md#class-eventemitter
49785034
[`Readable`]: #class-streamreadable
5035+
[`Stream.toAsyncStreamable`]: stream_iter.md#streamtoasyncstreamable
49795036
[`Symbol.hasInstance`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/hasInstance
49805037
[`Transform`]: #class-streamtransform
49815038
[`Writable`]: #class-streamwritable
@@ -5001,6 +5058,7 @@ contain multi-byte characters.
50015058
[`stream.uncork()`]: #writableuncork
50025059
[`stream.unpipe()`]: #readableunpipedestination
50035060
[`stream.wrap()`]: #readablewrapstream
5061+
[`stream/iter`]: stream_iter.md
50045062
[`writable._final()`]: #writable_finalcallback
50055063
[`writable._write()`]: #writable_writechunk-encoding-callback
50065064
[`writable._writev()`]: #writable_writevchunks-callback
@@ -5029,6 +5087,7 @@ contain multi-byte characters.
50295087
[stream-end]: #writableendchunk-encoding-callback
50305088
[stream-finished]: #streamfinishedstream-options-callback
50315089
[stream-finished-promise]: #streamfinishedstream-options
5090+
[stream-iter-from]: stream_iter.md#frominput
50325091
[stream-pause]: #readablepause
50335092
[stream-pipeline]: #streampipelinesource-transforms-destination-callback
50345093
[stream-pipeline-promise]: #streampipelinesource-transforms-destination-options

‎doc/api/stream_iter.md‎

Lines changed: 257 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1424,6 +1424,258 @@ Compression and decompression transforms for use with `pull()`, `pullSync()`,
14241424
`pipeTo()`, and `pipeToSync()` are available via the [`node:zlib/iter`][]
14251425
module. See the [`node:zlib/iter` documentation][] for details.
14261426

1427+
## Classic stream interop
1428+
1429+
These utility functions bridge between classic
1430+
[`stream.Readable`][]/[`stream.Writable`][] streams and the `stream/iter`
1431+
API.
1432+
1433+
Both `fromReadable()` and `fromWritable()` accept duck-typed objects -- they
1434+
do not require the input to extend `stream.Readable` or `stream.Writable`
1435+
directly. The minimum contract is described below for each function.
1436+
1437+
### `fromReadable(readable)`
1438+
1439+
<!-- YAML
1440+
added: REPLACEME
1441+
-->
1442+
1443+
> Stability: 1 - Experimental
1444+
1445+
*`readable` {stream.Readable|Object} A classic Readable stream or any object
1446+
with `read()` and `on()` methods.
1447+
* Returns: {AsyncIterable\<Uint8Array\[]>} A stream/iter async iterable source.
1448+
1449+
Converts a classic Readable stream (or duck-typed equivalent) into a
1450+
stream/iter async iterable source that can be passed to [`from()`][],
1451+
[`pull()`][], [`text()`][], etc.
1452+
1453+
If the object implements the [`toAsyncStreamable`][] protocol (as
1454+
`stream.Readable` does), that protocol is used. Otherwise, the function
1455+
duck-types on `read()` and `on()` (EventEmitter) and wraps the stream with
1456+
a batched async iterator.
1457+
1458+
The result is cached per instance -- calling `fromReadable()` twice with the
1459+
same stream returns the same iterable.
1460+
1461+
For object-mode or encoded Readable streams, chunks are automatically
1462+
normalized to `Uint8Array`.
1463+
1464+
```mjs
1465+
import { Readable } from'node:stream';
1466+
import { fromReadable, text } from'node:stream/iter';
1467+
1468+
constreadable=newReadable({
1469+
read() { this.push('hello world'); this.push(null); },
1470+
});
1471+
1472+
constresult=awaittext(fromReadable(readable));
1473+
console.log(result); // 'hello world'
1474+
```
1475+
1476+
```cjs
1477+
const { Readable } =require('node:stream');
1478+
const { fromReadable, text } =require('node:stream/iter');
1479+
1480+
constreadable=newReadable({
1481+
read() { this.push('hello world'); this.push(null); },
1482+
});
1483+
1484+
asyncfunctionrun() {
1485+
constresult=awaittext(fromReadable(readable));
1486+
console.log(result); // 'hello world'
1487+
}
1488+
run();
1489+
```
1490+
1491+
### `fromWritable(writable[, options])`
1492+
1493+
<!-- YAML
1494+
added: REPLACEME
1495+
-->
1496+
1497+
> Stability: 1 - Experimental
1498+
1499+
*`writable` {stream.Writable|Object} A classic Writable stream or any object
1500+
with `write()` and `on()` methods.
1501+
*`options` {Object}
1502+
*`backpressure` {string} Backpressure policy. **Default:**`'strict'`.
1503+
*`'strict'` -- writes are rejected when the buffer is full. Catches
1504+
callers that ignore backpressure.
1505+
*`'block'` -- writes wait for drain when the buffer is full. Recommended
1506+
for use with [`pipeTo()`][].
1507+
*`'drop-newest'` -- writes are silently discarded when the buffer is full.
1508+
*`'drop-oldest'` -- **not supported**. Throws `ERR_INVALID_ARG_VALUE`.
1509+
* Returns: {Object} A stream/iter Writer adapter.
1510+
1511+
Creates a stream/iter Writer adapter from a classic Writable stream (or
1512+
duck-typed equivalent). The adapter can be passed to [`pipeTo()`][] as a
1513+
destination.
1514+
1515+
Since all writes on a classic Writable are fundamentally asynchronous,
1516+
the synchronous Writer methods (`writeSync`, `writevSync`, `endSync`) always
1517+
return `false` or `-1`, deferring to the async path. The per-write
1518+
`options.signal` parameter from the Writer interface is also ignored.
1519+
1520+
The result is cached per instance -- calling `fromWritable()` twice with the
1521+
same stream returns the same Writer.
1522+
1523+
For duck-typed streams that do not expose `writableHighWaterMark`,
1524+
`writableLength`, or similar properties, sensible defaults are used.
1525+
Object-mode writables (if detectable) are rejected since the Writer
1526+
interface is bytes-only.
1527+
1528+
```mjs
1529+
import { Writable } from'node:stream';
1530+
import { from, fromWritable, pipeTo } from'node:stream/iter';
1531+
1532+
constwritable=newWritable({
1533+
write(chunk, encoding, cb) { console.log(chunk.toString()); cb(); },
1534+
});
1535+
1536+
awaitpipeTo(from('hello world'),
1537+
fromWritable(writable, { backpressure:'block' }));
1538+
```
1539+
1540+
```cjs
1541+
const { Writable } =require('node:stream');
1542+
const { from, fromWritable, pipeTo } =require('node:stream/iter');
1543+
1544+
asyncfunctionrun() {
1545+
constwritable=newWritable({
1546+
write(chunk, encoding, cb) { console.log(chunk.toString()); cb(); },
1547+
});
1548+
1549+
awaitpipeTo(from('hello world'),
1550+
fromWritable(writable, { backpressure:'block' }));
1551+
}
1552+
run();
1553+
```
1554+
1555+
### `toReadable(source[, options])`
1556+
1557+
<!-- YAML
1558+
added: REPLACEME
1559+
-->
1560+
1561+
> Stability: 1 - Experimental
1562+
1563+
*`source` {AsyncIterable} An `AsyncIterable<Uint8Array[]>` source, such as
1564+
the return value of [`pull()`][] or [`from()`][].
1565+
*`options` {Object}
1566+
*`highWaterMark` {number} The internal buffer size in bytes before
1567+
backpressure is applied. **Default:**`65536` (64 KB).
1568+
*`signal` {AbortSignal} An optional signal to abort the readable.
1569+
* Returns: {stream.Readable}
1570+
1571+
Creates a byte-mode [`stream.Readable`][] from an `AsyncIterable<Uint8Array[]>`
1572+
(the native batch format used by the stream/iter API). Each `Uint8Array` in a
1573+
yielded batch is pushed as a separate chunk into the Readable.
1574+
1575+
```mjs
1576+
import { createWriteStream } from'node:fs';
1577+
import { from, pull, toReadable } from'node:stream/iter';
1578+
import { compressGzip } from'node:zlib/iter';
1579+
1580+
constsource=pull(from('hello world'), compressGzip());
1581+
constreadable=toReadable(source);
1582+
1583+
readable.pipe(createWriteStream('output.gz'));
1584+
```
1585+
1586+
```cjs
1587+
const { createWriteStream } =require('node:fs');
1588+
const { from, pull, toReadable } =require('node:stream/iter');
1589+
const { compressGzip } =require('node:zlib/iter');
1590+
1591+
constsource=pull(from('hello world'), compressGzip());
1592+
constreadable=toReadable(source);
1593+
1594+
readable.pipe(createWriteStream('output.gz'));
1595+
```
1596+
1597+
### `toReadableSync(source[, options])`
1598+
1599+
<!-- YAML
1600+
added: REPLACEME
1601+
-->
1602+
1603+
> Stability: 1 - Experimental
1604+
1605+
*`source` {Iterable} An `Iterable<Uint8Array[]>` source, such as the
1606+
return value of [`pullSync()`][] or [`fromSync()`][].
1607+
*`options` {Object}
1608+
*`highWaterMark` {number} The internal buffer size in bytes before
1609+
backpressure is applied. **Default:**`65536` (64 KB).
1610+
* Returns: {stream.Readable}
1611+
1612+
Creates a byte-mode [`stream.Readable`][] from a synchronous
1613+
`Iterable<Uint8Array[]>`. The `_read()` method pulls from the iterator
1614+
synchronously, so data is available immediately via `readable.read()`.
1615+
1616+
```mjs
1617+
import { fromSync, toReadableSync } from'node:stream/iter';
1618+
1619+
constsource=fromSync('hello world');
1620+
constreadable=toReadableSync(source);
1621+
1622+
console.log(readable.read().toString()); // 'hello world'
1623+
```
1624+
1625+
```cjs
1626+
const { fromSync, toReadableSync } =require('node:stream/iter');
1627+
1628+
constsource=fromSync('hello world');
1629+
constreadable=toReadableSync(source);
1630+
1631+
console.log(readable.read().toString()); // 'hello world'
1632+
```
1633+
1634+
### `toWritable(writer)`
1635+
1636+
<!-- YAML
1637+
added: REPLACEME
1638+
-->
1639+
1640+
> Stability: 1 - Experimental
1641+
1642+
*`writer` {Object} A stream/iter Writer. Only the `write()` method is
1643+
required; `end()`, `fail()`, `writeSync()`, `writevSync()`, `endSync()`,
1644+
and `writev()` are optional.
1645+
* Returns: {stream.Writable}
1646+
1647+
Creates a classic [`stream.Writable`][] backed by a stream/iter Writer.
1648+
1649+
Each `_write()` / `_writev()` call attempts the Writer's synchronous method
1650+
first (`writeSync` / `writevSync`), falling back to the async method if the
1651+
sync path returns `false` or throws. Similarly, `_final()` tries `endSync()`
1652+
before `end()`. When the sync path succeeds, the callback is deferred via
1653+
`queueMicrotask` to preserve the async resolution contract.
1654+
1655+
The Writable's `highWaterMark` is set to `Number.MAX_SAFE_INTEGER` to
1656+
effectively disable its internal buffering, allowing the underlying Writer
1657+
to manage backpressure directly.
1658+
1659+
```mjs
1660+
import { push, toWritable } from'node:stream/iter';
1661+
1662+
const { writer, readable } =push();
1663+
constwritable=toWritable(writer);
1664+
1665+
writable.write('hello');
1666+
writable.end();
1667+
```
1668+
1669+
```cjs
1670+
const { push, toWritable } =require('node:stream/iter');
1671+
1672+
const { writer, readable } =push();
1673+
constwritable=toWritable(writer);
1674+
1675+
writable.write('hello');
1676+
writable.end();
1677+
```
1678+
14271679
## Protocol symbols
14281680

14291681
These well-known symbols allow third-party objects to participate in the
@@ -1816,10 +2068,15 @@ console.log(textSync(stream)); // 'hello world'
18162068
[`arrayBuffer()`]: #arraybuffersource-options
18172069
[`bytes()`]: #bytessource-options
18182070
[`from()`]: #frominput
2071+
[`fromSync()`]: #fromsyncinput
18192072
[`node:zlib/iter`]: zlib_iter.md
18202073
[`node:zlib/iter` documentation]: zlib_iter.md
18212074
[`pipeTo()`]: #pipetosource-transforms-writer-options
18222075
[`pull()`]: #pullsource-transforms-options
2076+
[`pullSync()`]: #pullsyncsource-transforms-options
18232077
[`share()`]: #sharesource-options
2078+
[`stream.Readable`]: stream.md#class-streamreadable
2079+
[`stream.Writable`]: stream.md#class-streamwritable
18242080
[`tap()`]: #tapcallback
18252081
[`text()`]: #textsource-options
2082+
[`toAsyncStreamable`]: #streamtoasyncstreamable

‎lib/internal/errors.js‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1775,6 +1775,8 @@ E('ERR_STREAM_ALREADY_FINISHED',
17751775
Error);
17761776
E('ERR_STREAM_CANNOT_PIPE','Cannot pipe, not readable',Error);
17771777
E('ERR_STREAM_DESTROYED','Cannot call %s after a stream was destroyed',Error);
1778+
E('ERR_STREAM_ITER_MISSING_FLAG',
1779+
'The stream/iter API requires the --experimental-stream-iter flag',TypeError);
17781780
E('ERR_STREAM_NULL_VALUES','May not write null values to stream',TypeError);
17791781
E('ERR_STREAM_PREMATURE_CLOSE','Premature close',Error);
17801782
E('ERR_STREAM_PUSH_AFTER_EOF','stream.push() after EOF',Error);

0 commit comments

Comments
 (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Commit baf98fa

Browse files
jasnelladuh95
authored andcommitted
stream: add stream/iter to classic stream adapters
Signed-off-by: James M Snell <jasnell@gmail.com> Assisted-by: Opencode/Opus 4.6 PR-URL: #62469 Backport-PR-URL: #64675 Reviewed-By: Robert Nagy <ronagy@icloud.com>
1 parent a290f51 commit baf98fa

17 files changed

Lines changed: 3848 additions & 14 deletions

‎doc/api/errors.md‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2906,6 +2906,13 @@ An attempt was made to call [`stream.pipe()`][] on a [`Writable`][] stream.
29062906
A stream method was called that cannot complete because the stream was
29072907
destroyed using `stream.destroy()`.
29082908

2909+
<aid="ERR_STREAM_ITER_MISSING_FLAG"></a>
2910+
2911+
### `ERR_STREAM_ITER_MISSING_FLAG`
2912+
2913+
A stream/iter API was used without the `--experimental-stream-iter` CLI flag
2914+
enabled.
2915+
29092916
<aid="ERR_STREAM_NULL_VALUES"></a>
29102917

29112918
### `ERR_STREAM_NULL_VALUES`

‎doc/api/stream.md‎

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1998,6 +1998,61 @@ option. In the code example above, data will be in a single chunk if the file
19981998
has less then 64 KiB of data because no `highWaterMark` option is provided to
19991999
[`fs.createReadStream()`][].
20002000

2001+
##### `readable[Symbol.for('Stream.toAsyncStreamable')]()`
2002+
2003+
<!-- YAML
2004+
added: REPLACEME
2005+
-->
2006+
2007+
> Stability: 1 - Experimental
2008+
2009+
* Returns: {AsyncIterable} An `AsyncIterable<Uint8Array[]>` that yields
2010+
batched chunks from the stream.
2011+
2012+
When the `--experimental-stream-iter` flag is enabled, `Readable` streams
2013+
implement the [`Stream.toAsyncStreamable`][] protocol, enabling efficient
2014+
consumption by the [`stream/iter`][] API.
2015+
2016+
This provides a batched async iterator that drains the stream's internal
2017+
buffer into `Uint8Array[]` batches, amortizing the per-chunk Promise overhead
2018+
of the standard `Symbol.asyncIterator` path. For byte-mode streams, chunks
2019+
are yielded directly as `Buffer` instances (which are `Uint8Array` subclasses).
2020+
For object-mode or encoded streams, each chunk is normalized to `Uint8Array`
2021+
before batching.
2022+
2023+
The returned iterator is tagged as a validated source, so [`from()`][stream-iter-from]
2024+
passes it through without additional normalization.
2025+
2026+
```mjs
2027+
import { Readable } from'node:stream';
2028+
import { text, from } from'node:stream/iter';
2029+
2030+
constreadable=newReadable({
2031+
read() { this.push('hello'); this.push(null); },
2032+
});
2033+
2034+
// Readable is automatically consumed via toAsyncStreamable
2035+
console.log(awaittext(from(readable))); // 'hello'
2036+
```
2037+
2038+
```cjs
2039+
const { Readable } =require('node:stream');
2040+
const { text, from } =require('node:stream/iter');
2041+
2042+
asyncfunctionrun() {
2043+
constreadable=newReadable({
2044+
read() { this.push('hello'); this.push(null); },
2045+
});
2046+
2047+
console.log(awaittext(from(readable))); // 'hello'
2048+
}
2049+
2050+
run().catch(console.error);
2051+
```
2052+
2053+
Without the `--experimental-stream-iter` flag, calling this method throws
2054+
[`ERR_STREAM_ITER_MISSING_FLAG`][].
2055+
20012056
##### `readable[Symbol.asyncDispose]()`
20022057

20032058
<!-- YAML
@@ -4974,8 +5029,10 @@ contain multi-byte characters.
49745029
[`'finish'`]: #event-finish
49755030
[`'readable'`]: #event-readable
49765031
[`Duplex`]: #class-streamduplex
5032+
[`ERR_STREAM_ITER_MISSING_FLAG`]: errors.md#err_stream_iter_missing_flag
49775033
[`EventEmitter`]: events.md#class-eventemitter
49785034
[`Readable`]: #class-streamreadable
5035+
[`Stream.toAsyncStreamable`]: stream_iter.md#streamtoasyncstreamable
49795036
[`Symbol.hasInstance`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/hasInstance
49805037
[`Transform`]: #class-streamtransform
49815038
[`Writable`]: #class-streamwritable
@@ -5001,6 +5058,7 @@ contain multi-byte characters.
50015058
[`stream.uncork()`]: #writableuncork
50025059
[`stream.unpipe()`]: #readableunpipedestination
50035060
[`stream.wrap()`]: #readablewrapstream
5061+
[`stream/iter`]: stream_iter.md
50045062
[`writable._final()`]: #writable_finalcallback
50055063
[`writable._write()`]: #writable_writechunk-encoding-callback
50065064
[`writable._writev()`]: #writable_writevchunks-callback
@@ -5029,6 +5087,7 @@ contain multi-byte characters.
50295087
[stream-end]: #writableendchunk-encoding-callback
50305088
[stream-finished]: #streamfinishedstream-options-callback
50315089
[stream-finished-promise]: #streamfinishedstream-options
5090+
[stream-iter-from]: stream_iter.md#frominput
50325091
[stream-pause]: #readablepause
50335092
[stream-pipeline]: #streampipelinesource-transforms-destination-callback
50345093
[stream-pipeline-promise]: #streampipelinesource-transforms-destination-options

‎doc/api/stream_iter.md‎

Lines changed: 257 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1424,6 +1424,258 @@ Compression and decompression transforms for use with `pull()`, `pullSync()`,
14241424
`pipeTo()`, and `pipeToSync()` are available via the [`node:zlib/iter`][]
14251425
module. See the [`node:zlib/iter` documentation][] for details.
14261426

1427+
## Classic stream interop
1428+
1429+
These utility functions bridge between classic
1430+
[`stream.Readable`][]/[`stream.Writable`][] streams and the `stream/iter`
1431+
API.
1432+
1433+
Both `fromReadable()` and `fromWritable()` accept duck-typed objects -- they
1434+
do not require the input to extend `stream.Readable` or `stream.Writable`
1435+
directly. The minimum contract is described below for each function.
1436+
1437+
### `fromReadable(readable)`
1438+
1439+
<!-- YAML
1440+
added: REPLACEME
1441+
-->
1442+
1443+
> Stability: 1 - Experimental
1444+
1445+
*`readable` {stream.Readable|Object} A classic Readable stream or any object
1446+
with `read()` and `on()` methods.
1447+
* Returns: {AsyncIterable\<Uint8Array\[]>} A stream/iter async iterable source.
1448+
1449+
Converts a classic Readable stream (or duck-typed equivalent) into a
1450+
stream/iter async iterable source that can be passed to [`from()`][],
1451+
[`pull()`][], [`text()`][], etc.
1452+
1453+
If the object implements the [`toAsyncStreamable`][] protocol (as
1454+
`stream.Readable` does), that protocol is used. Otherwise, the function
1455+
duck-types on `read()` and `on()` (EventEmitter) and wraps the stream with
1456+
a batched async iterator.
1457+
1458+
The result is cached per instance -- calling `fromReadable()` twice with the
1459+
same stream returns the same iterable.
1460+
1461+
For object-mode or encoded Readable streams, chunks are automatically
1462+
normalized to `Uint8Array`.
1463+
1464+
```mjs
1465+
import { Readable } from'node:stream';
1466+
import { fromReadable, text } from'node:stream/iter';
1467+
1468+
constreadable=newReadable({
1469+
read() { this.push('hello world'); this.push(null); },
1470+
});
1471+
1472+
constresult=awaittext(fromReadable(readable));
1473+
console.log(result); // 'hello world'
1474+
```
1475+
1476+
```cjs
1477+
const { Readable } =require('node:stream');
1478+
const { fromReadable, text } =require('node:stream/iter');
1479+
1480+
constreadable=newReadable({
1481+
read() { this.push('hello world'); this.push(null); },
1482+
});
1483+
1484+
asyncfunctionrun() {
1485+
constresult=awaittext(fromReadable(readable));
1486+
console.log(result); // 'hello world'
1487+
}
1488+
run();
1489+
```
1490+
1491+
### `fromWritable(writable[, options])`
1492+
1493+
<!-- YAML
1494+
added: REPLACEME
1495+
-->
1496+
1497+
> Stability: 1 - Experimental
1498+
1499+
*`writable` {stream.Writable|Object} A classic Writable stream or any object
1500+
with `write()` and `on()` methods.
1501+
*`options` {Object}
1502+
*`backpressure` {string} Backpressure policy. **Default:**`'strict'`.
1503+
*`'strict'` -- writes are rejected when the buffer is full. Catches
1504+
callers that ignore backpressure.
1505+
*`'block'` -- writes wait for drain when the buffer is full. Recommended
1506+
for use with [`pipeTo()`][].
1507+
*`'drop-newest'` -- writes are silently discarded when the buffer is full.
1508+
*`'drop-oldest'` -- **not supported**. Throws `ERR_INVALID_ARG_VALUE`.
1509+
* Returns: {Object} A stream/iter Writer adapter.
1510+
1511+
Creates a stream/iter Writer adapter from a classic Writable stream (or
1512+
duck-typed equivalent). The adapter can be passed to [`pipeTo()`][] as a
1513+
destination.
1514+
1515+
Since all writes on a classic Writable are fundamentally asynchronous,
1516+
the synchronous Writer methods (`writeSync`, `writevSync`, `endSync`) always
1517+
return `false` or `-1`, deferring to the async path. The per-write
1518+
`options.signal` parameter from the Writer interface is also ignored.
1519+
1520+
The result is cached per instance -- calling `fromWritable()` twice with the
1521+
same stream returns the same Writer.
1522+
1523+
For duck-typed streams that do not expose `writableHighWaterMark`,
1524+
`writableLength`, or similar properties, sensible defaults are used.
1525+
Object-mode writables (if detectable) are rejected since the Writer
1526+
interface is bytes-only.
1527+
1528+
```mjs
1529+
import { Writable } from'node:stream';
1530+
import { from, fromWritable, pipeTo } from'node:stream/iter';
1531+
1532+
constwritable=newWritable({
1533+
write(chunk, encoding, cb) { console.log(chunk.toString()); cb(); },
1534+
});
1535+
1536+
awaitpipeTo(from('hello world'),
1537+
fromWritable(writable, { backpressure:'block' }));
1538+
```
1539+
1540+
```cjs
1541+
const { Writable } =require('node:stream');
1542+
const { from, fromWritable, pipeTo } =require('node:stream/iter');
1543+
1544+
asyncfunctionrun() {
1545+
constwritable=newWritable({
1546+
write(chunk, encoding, cb) { console.log(chunk.toString()); cb(); },
1547+
});
1548+
1549+
awaitpipeTo(from('hello world'),
1550+
fromWritable(writable, { backpressure:'block' }));
1551+
}
1552+
run();
1553+
```
1554+
1555+
### `toReadable(source[, options])`
1556+
1557+
<!-- YAML
1558+
added: REPLACEME
1559+
-->
1560+
1561+
> Stability: 1 - Experimental
1562+
1563+
*`source` {AsyncIterable} An `AsyncIterable<Uint8Array[]>` source, such as
1564+
the return value of [`pull()`][] or [`from()`][].
1565+
*`options` {Object}
1566+
*`highWaterMark` {number} The internal buffer size in bytes before
1567+
backpressure is applied. **Default:**`65536` (64 KB).
1568+
*`signal` {AbortSignal} An optional signal to abort the readable.
1569+
* Returns: {stream.Readable}
1570+
1571+
Creates a byte-mode [`stream.Readable`][] from an `AsyncIterable<Uint8Array[]>`
1572+
(the native batch format used by the stream/iter API). Each `Uint8Array` in a
1573+
yielded batch is pushed as a separate chunk into the Readable.
1574+
1575+
```mjs
1576+
import { createWriteStream } from'node:fs';
1577+
import { from, pull, toReadable } from'node:stream/iter';
1578+
import { compressGzip } from'node:zlib/iter';
1579+
1580+
constsource=pull(from('hello world'), compressGzip());
1581+
constreadable=toReadable(source);
1582+
1583+
readable.pipe(createWriteStream('output.gz'));
1584+
```
1585+
1586+
```cjs
1587+
const { createWriteStream } =require('node:fs');
1588+
const { from, pull, toReadable } =require('node:stream/iter');
1589+
const { compressGzip } =require('node:zlib/iter');
1590+
1591+
constsource=pull(from('hello world'), compressGzip());
1592+
constreadable=toReadable(source);
1593+
1594+
readable.pipe(createWriteStream('output.gz'));
1595+
```
1596+
1597+
### `toReadableSync(source[, options])`
1598+
1599+
<!-- YAML
1600+
added: REPLACEME
1601+
-->
1602+
1603+
> Stability: 1 - Experimental
1604+
1605+
*`source` {Iterable} An `Iterable<Uint8Array[]>` source, such as the
1606+
return value of [`pullSync()`][] or [`fromSync()`][].
1607+
*`options` {Object}
1608+
*`highWaterMark` {number} The internal buffer size in bytes before
1609+
backpressure is applied. **Default:**`65536` (64 KB).
1610+
* Returns: {stream.Readable}
1611+
1612+
Creates a byte-mode [`stream.Readable`][] from a synchronous
1613+
`Iterable<Uint8Array[]>`. The `_read()` method pulls from the iterator
1614+
synchronously, so data is available immediately via `readable.read()`.
1615+
1616+
```mjs
1617+
import { fromSync, toReadableSync } from'node:stream/iter';
1618+
1619+
constsource=fromSync('hello world');
1620+
constreadable=toReadableSync(source);
1621+
1622+
console.log(readable.read().toString()); // 'hello world'
1623+
```
1624+
1625+
```cjs
1626+
const { fromSync, toReadableSync } =require('node:stream/iter');
1627+
1628+
constsource=fromSync('hello world');
1629+
constreadable=toReadableSync(source);
1630+
1631+
console.log(readable.read().toString()); // 'hello world'
1632+
```
1633+
1634+
### `toWritable(writer)`
1635+
1636+
<!-- YAML
1637+
added: REPLACEME
1638+
-->
1639+
1640+
> Stability: 1 - Experimental
1641+
1642+
*`writer` {Object} A stream/iter Writer. Only the `write()` method is
1643+
required; `end()`, `fail()`, `writeSync()`, `writevSync()`, `endSync()`,
1644+
and `writev()` are optional.
1645+
* Returns: {stream.Writable}
1646+
1647+
Creates a classic [`stream.Writable`][] backed by a stream/iter Writer.
1648+
1649+
Each `_write()` / `_writev()` call attempts the Writer's synchronous method
1650+
first (`writeSync` / `writevSync`), falling back to the async method if the
1651+
sync path returns `false` or throws. Similarly, `_final()` tries `endSync()`
1652+
before `end()`. When the sync path succeeds, the callback is deferred via
1653+
`queueMicrotask` to preserve the async resolution contract.
1654+
1655+
The Writable's `highWaterMark` is set to `Number.MAX_SAFE_INTEGER` to
1656+
effectively disable its internal buffering, allowing the underlying Writer
1657+
to manage backpressure directly.
1658+
1659+
```mjs
1660+
import { push, toWritable } from'node:stream/iter';
1661+
1662+
const { writer, readable } =push();
1663+
constwritable=toWritable(writer);
1664+
1665+
writable.write('hello');
1666+
writable.end();
1667+
```
1668+
1669+
```cjs
1670+
const { push, toWritable } =require('node:stream/iter');
1671+
1672+
const { writer, readable } =push();
1673+
constwritable=toWritable(writer);
1674+
1675+
writable.write('hello');
1676+
writable.end();
1677+
```
1678+
14271679
## Protocol symbols
14281680

14291681
These well-known symbols allow third-party objects to participate in the
@@ -1816,10 +2068,15 @@ console.log(textSync(stream)); // 'hello world'
18162068
[`arrayBuffer()`]: #arraybuffersource-options
18172069
[`bytes()`]: #bytessource-options
18182070
[`from()`]: #frominput
2071+
[`fromSync()`]: #fromsyncinput
18192072
[`node:zlib/iter`]: zlib_iter.md
18202073
[`node:zlib/iter` documentation]: zlib_iter.md
18212074
[`pipeTo()`]: #pipetosource-transforms-writer-options
18222075
[`pull()`]: #pullsource-transforms-options
2076+
[`pullSync()`]: #pullsyncsource-transforms-options
18232077
[`share()`]: #sharesource-options
2078+
[`stream.Readable`]: stream.md#class-streamreadable
2079+
[`stream.Writable`]: stream.md#class-streamwritable
18242080
[`tap()`]: #tapcallback
18252081
[`text()`]: #textsource-options
2082+
[`toAsyncStreamable`]: #streamtoasyncstreamable

‎lib/internal/errors.js‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1775,6 +1775,8 @@ E('ERR_STREAM_ALREADY_FINISHED',
17751775
Error);
17761776
E('ERR_STREAM_CANNOT_PIPE','Cannot pipe, not readable',Error);
17771777
E('ERR_STREAM_DESTROYED','Cannot call %s after a stream was destroyed',Error);
1778+
E('ERR_STREAM_ITER_MISSING_FLAG',
1779+
'The stream/iter API requires the --experimental-stream-iter flag',TypeError);
17781780
E('ERR_STREAM_NULL_VALUES','May not write null values to stream',TypeError);
17791781
E('ERR_STREAM_PREMATURE_CLOSE','Premature close',Error);
17801782
E('ERR_STREAM_PUSH_AFTER_EOF','stream.push() after EOF',Error);

0 commit comments

Comments
 (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Commit baf98fa

Browse files
jasnelladuh95
authored andcommitted
stream: add stream/iter to classic stream adapters
Signed-off-by: James M Snell <jasnell@gmail.com> Assisted-by: Opencode/Opus 4.6 PR-URL: #62469 Backport-PR-URL: #64675 Reviewed-By: Robert Nagy <ronagy@icloud.com>
1 parent a290f51 commit baf98fa

17 files changed

Lines changed: 3848 additions & 14 deletions

‎doc/api/errors.md‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2906,6 +2906,13 @@ An attempt was made to call [`stream.pipe()`][] on a [`Writable`][] stream.
29062906
A stream method was called that cannot complete because the stream was
29072907
destroyed using `stream.destroy()`.
29082908

2909+
<aid="ERR_STREAM_ITER_MISSING_FLAG"></a>
2910+
2911+
### `ERR_STREAM_ITER_MISSING_FLAG`
2912+
2913+
A stream/iter API was used without the `--experimental-stream-iter` CLI flag
2914+
enabled.
2915+
29092916
<aid="ERR_STREAM_NULL_VALUES"></a>
29102917

29112918
### `ERR_STREAM_NULL_VALUES`

‎doc/api/stream.md‎

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1998,6 +1998,61 @@ option. In the code example above, data will be in a single chunk if the file
19981998
has less then 64 KiB of data because no `highWaterMark` option is provided to
19991999
[`fs.createReadStream()`][].
20002000

2001+
##### `readable[Symbol.for('Stream.toAsyncStreamable')]()`
2002+
2003+
<!-- YAML
2004+
added: REPLACEME
2005+
-->
2006+
2007+
> Stability: 1 - Experimental
2008+
2009+
* Returns: {AsyncIterable} An `AsyncIterable<Uint8Array[]>` that yields
2010+
batched chunks from the stream.
2011+
2012+
When the `--experimental-stream-iter` flag is enabled, `Readable` streams
2013+
implement the [`Stream.toAsyncStreamable`][] protocol, enabling efficient
2014+
consumption by the [`stream/iter`][] API.
2015+
2016+
This provides a batched async iterator that drains the stream's internal
2017+
buffer into `Uint8Array[]` batches, amortizing the per-chunk Promise overhead
2018+
of the standard `Symbol.asyncIterator` path. For byte-mode streams, chunks
2019+
are yielded directly as `Buffer` instances (which are `Uint8Array` subclasses).
2020+
For object-mode or encoded streams, each chunk is normalized to `Uint8Array`
2021+
before batching.
2022+
2023+
The returned iterator is tagged as a validated source, so [`from()`][stream-iter-from]
2024+
passes it through without additional normalization.
2025+
2026+
```mjs
2027+
import { Readable } from'node:stream';
2028+
import { text, from } from'node:stream/iter';
2029+
2030+
constreadable=newReadable({
2031+
read() { this.push('hello'); this.push(null); },
2032+
});
2033+
2034+
// Readable is automatically consumed via toAsyncStreamable
2035+
console.log(awaittext(from(readable))); // 'hello'
2036+
```
2037+
2038+
```cjs
2039+
const { Readable } =require('node:stream');
2040+
const { text, from } =require('node:stream/iter');
2041+
2042+
asyncfunctionrun() {
2043+
constreadable=newReadable({
2044+
read() { this.push('hello'); this.push(null); },
2045+
});
2046+
2047+
console.log(awaittext(from(readable))); // 'hello'
2048+
}
2049+
2050+
run().catch(console.error);
2051+
```
2052+
2053+
Without the `--experimental-stream-iter` flag, calling this method throws
2054+
[`ERR_STREAM_ITER_MISSING_FLAG`][].
2055+
20012056
##### `readable[Symbol.asyncDispose]()`
20022057

20032058
<!-- YAML
@@ -4974,8 +5029,10 @@ contain multi-byte characters.
49745029
[`'finish'`]: #event-finish
49755030
[`'readable'`]: #event-readable
49765031
[`Duplex`]: #class-streamduplex
5032+
[`ERR_STREAM_ITER_MISSING_FLAG`]: errors.md#err_stream_iter_missing_flag
49775033
[`EventEmitter`]: events.md#class-eventemitter
49785034
[`Readable`]: #class-streamreadable
5035+
[`Stream.toAsyncStreamable`]: stream_iter.md#streamtoasyncstreamable
49795036
[`Symbol.hasInstance`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/hasInstance
49805037
[`Transform`]: #class-streamtransform
49815038
[`Writable`]: #class-streamwritable
@@ -5001,6 +5058,7 @@ contain multi-byte characters.
50015058
[`stream.uncork()`]: #writableuncork
50025059
[`stream.unpipe()`]: #readableunpipedestination
50035060
[`stream.wrap()`]: #readablewrapstream
5061+
[`stream/iter`]: stream_iter.md
50045062
[`writable._final()`]: #writable_finalcallback
50055063
[`writable._write()`]: #writable_writechunk-encoding-callback
50065064
[`writable._writev()`]: #writable_writevchunks-callback
@@ -5029,6 +5087,7 @@ contain multi-byte characters.
50295087
[stream-end]: #writableendchunk-encoding-callback
50305088
[stream-finished]: #streamfinishedstream-options-callback
50315089
[stream-finished-promise]: #streamfinishedstream-options
5090+
[stream-iter-from]: stream_iter.md#frominput
50325091
[stream-pause]: #readablepause
50335092
[stream-pipeline]: #streampipelinesource-transforms-destination-callback
50345093
[stream-pipeline-promise]: #streampipelinesource-transforms-destination-options

‎doc/api/stream_iter.md‎

Lines changed: 257 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1424,6 +1424,258 @@ Compression and decompression transforms for use with `pull()`, `pullSync()`,
14241424
`pipeTo()`, and `pipeToSync()` are available via the [`node:zlib/iter`][]
14251425
module. See the [`node:zlib/iter` documentation][] for details.
14261426

1427+
## Classic stream interop
1428+
1429+
These utility functions bridge between classic
1430+
[`stream.Readable`][]/[`stream.Writable`][] streams and the `stream/iter`
1431+
API.
1432+
1433+
Both `fromReadable()` and `fromWritable()` accept duck-typed objects -- they
1434+
do not require the input to extend `stream.Readable` or `stream.Writable`
1435+
directly. The minimum contract is described below for each function.
1436+
1437+
### `fromReadable(readable)`
1438+
1439+
<!-- YAML
1440+
added: REPLACEME
1441+
-->
1442+
1443+
> Stability: 1 - Experimental
1444+
1445+
*`readable` {stream.Readable|Object} A classic Readable stream or any object
1446+
with `read()` and `on()` methods.
1447+
* Returns: {AsyncIterable\<Uint8Array\[]>} A stream/iter async iterable source.
1448+
1449+
Converts a classic Readable stream (or duck-typed equivalent) into a
1450+
stream/iter async iterable source that can be passed to [`from()`][],
1451+
[`pull()`][], [`text()`][], etc.
1452+
1453+
If the object implements the [`toAsyncStreamable`][] protocol (as
1454+
`stream.Readable` does), that protocol is used. Otherwise, the function
1455+
duck-types on `read()` and `on()` (EventEmitter) and wraps the stream with
1456+
a batched async iterator.
1457+
1458+
The result is cached per instance -- calling `fromReadable()` twice with the
1459+
same stream returns the same iterable.
1460+
1461+
For object-mode or encoded Readable streams, chunks are automatically
1462+
normalized to `Uint8Array`.
1463+
1464+
```mjs
1465+
import { Readable } from'node:stream';
1466+
import { fromReadable, text } from'node:stream/iter';
1467+
1468+
constreadable=newReadable({
1469+
read() { this.push('hello world'); this.push(null); },
1470+
});
1471+
1472+
constresult=awaittext(fromReadable(readable));
1473+
console.log(result); // 'hello world'
1474+
```
1475+
1476+
```cjs
1477+
const { Readable } =require('node:stream');
1478+
const { fromReadable, text } =require('node:stream/iter');
1479+
1480+
constreadable=newReadable({
1481+
read() { this.push('hello world'); this.push(null); },
1482+
});
1483+
1484+
asyncfunctionrun() {
1485+
constresult=awaittext(fromReadable(readable));
1486+
console.log(result); // 'hello world'
1487+
}
1488+
run();
1489+
```
1490+
1491+
### `fromWritable(writable[, options])`
1492+
1493+
<!-- YAML
1494+
added: REPLACEME
1495+
-->
1496+
1497+
> Stability: 1 - Experimental
1498+
1499+
*`writable` {stream.Writable|Object} A classic Writable stream or any object
1500+
with `write()` and `on()` methods.
1501+
*`options` {Object}
1502+
*`backpressure` {string} Backpressure policy. **Default:**`'strict'`.
1503+
*`'strict'` -- writes are rejected when the buffer is full. Catches
1504+
callers that ignore backpressure.
1505+
*`'block'` -- writes wait for drain when the buffer is full. Recommended
1506+
for use with [`pipeTo()`][].
1507+
*`'drop-newest'` -- writes are silently discarded when the buffer is full.
1508+
*`'drop-oldest'` -- **not supported**. Throws `ERR_INVALID_ARG_VALUE`.
1509+
* Returns: {Object} A stream/iter Writer adapter.
1510+
1511+
Creates a stream/iter Writer adapter from a classic Writable stream (or
1512+
duck-typed equivalent). The adapter can be passed to [`pipeTo()`][] as a
1513+
destination.
1514+
1515+
Since all writes on a classic Writable are fundamentally asynchronous,
1516+
the synchronous Writer methods (`writeSync`, `writevSync`, `endSync`) always
1517+
return `false` or `-1`, deferring to the async path. The per-write
1518+
`options.signal` parameter from the Writer interface is also ignored.
1519+
1520+
The result is cached per instance -- calling `fromWritable()` twice with the
1521+
same stream returns the same Writer.
1522+
1523+
For duck-typed streams that do not expose `writableHighWaterMark`,
1524+
`writableLength`, or similar properties, sensible defaults are used.
1525+
Object-mode writables (if detectable) are rejected since the Writer
1526+
interface is bytes-only.
1527+
1528+
```mjs
1529+
import { Writable } from'node:stream';
1530+
import { from, fromWritable, pipeTo } from'node:stream/iter';
1531+
1532+
constwritable=newWritable({
1533+
write(chunk, encoding, cb) { console.log(chunk.toString()); cb(); },
1534+
});
1535+
1536+
awaitpipeTo(from('hello world'),
1537+
fromWritable(writable, { backpressure:'block' }));
1538+
```
1539+
1540+
```cjs
1541+
const { Writable } =require('node:stream');
1542+
const { from, fromWritable, pipeTo } =require('node:stream/iter');
1543+
1544+
asyncfunctionrun() {
1545+
constwritable=newWritable({
1546+
write(chunk, encoding, cb) { console.log(chunk.toString()); cb(); },
1547+
});
1548+
1549+
awaitpipeTo(from('hello world'),
1550+
fromWritable(writable, { backpressure:'block' }));
1551+
}
1552+
run();
1553+
```
1554+
1555+
### `toReadable(source[, options])`
1556+
1557+
<!-- YAML
1558+
added: REPLACEME
1559+
-->
1560+
1561+
> Stability: 1 - Experimental
1562+
1563+
*`source` {AsyncIterable} An `AsyncIterable<Uint8Array[]>` source, such as
1564+
the return value of [`pull()`][] or [`from()`][].
1565+
*`options` {Object}
1566+
*`highWaterMark` {number} The internal buffer size in bytes before
1567+
backpressure is applied. **Default:**`65536` (64 KB).
1568+
*`signal` {AbortSignal} An optional signal to abort the readable.
1569+
* Returns: {stream.Readable}
1570+
1571+
Creates a byte-mode [`stream.Readable`][] from an `AsyncIterable<Uint8Array[]>`
1572+
(the native batch format used by the stream/iter API). Each `Uint8Array` in a
1573+
yielded batch is pushed as a separate chunk into the Readable.
1574+
1575+
```mjs
1576+
import { createWriteStream } from'node:fs';
1577+
import { from, pull, toReadable } from'node:stream/iter';
1578+
import { compressGzip } from'node:zlib/iter';
1579+
1580+
constsource=pull(from('hello world'), compressGzip());
1581+
constreadable=toReadable(source);
1582+
1583+
readable.pipe(createWriteStream('output.gz'));
1584+
```
1585+
1586+
```cjs
1587+
const { createWriteStream } =require('node:fs');
1588+
const { from, pull, toReadable } =require('node:stream/iter');
1589+
const { compressGzip } =require('node:zlib/iter');
1590+
1591+
constsource=pull(from('hello world'), compressGzip());
1592+
constreadable=toReadable(source);
1593+
1594+
readable.pipe(createWriteStream('output.gz'));
1595+
```
1596+
1597+
### `toReadableSync(source[, options])`
1598+
1599+
<!-- YAML
1600+
added: REPLACEME
1601+
-->
1602+
1603+
> Stability: 1 - Experimental
1604+
1605+
*`source` {Iterable} An `Iterable<Uint8Array[]>` source, such as the
1606+
return value of [`pullSync()`][] or [`fromSync()`][].
1607+
*`options` {Object}
1608+
*`highWaterMark` {number} The internal buffer size in bytes before
1609+
backpressure is applied. **Default:**`65536` (64 KB).
1610+
* Returns: {stream.Readable}
1611+
1612+
Creates a byte-mode [`stream.Readable`][] from a synchronous
1613+
`Iterable<Uint8Array[]>`. The `_read()` method pulls from the iterator
1614+
synchronously, so data is available immediately via `readable.read()`.
1615+
1616+
```mjs
1617+
import { fromSync, toReadableSync } from'node:stream/iter';
1618+
1619+
constsource=fromSync('hello world');
1620+
constreadable=toReadableSync(source);
1621+
1622+
console.log(readable.read().toString()); // 'hello world'
1623+
```
1624+
1625+
```cjs
1626+
const { fromSync, toReadableSync } =require('node:stream/iter');
1627+
1628+
constsource=fromSync('hello world');
1629+
constreadable=toReadableSync(source);
1630+
1631+
console.log(readable.read().toString()); // 'hello world'
1632+
```
1633+
1634+
### `toWritable(writer)`
1635+
1636+
<!-- YAML
1637+
added: REPLACEME
1638+
-->
1639+
1640+
> Stability: 1 - Experimental
1641+
1642+
*`writer` {Object} A stream/iter Writer. Only the `write()` method is
1643+
required; `end()`, `fail()`, `writeSync()`, `writevSync()`, `endSync()`,
1644+
and `writev()` are optional.
1645+
* Returns: {stream.Writable}
1646+
1647+
Creates a classic [`stream.Writable`][] backed by a stream/iter Writer.
1648+
1649+
Each `_write()` / `_writev()` call attempts the Writer's synchronous method
1650+
first (`writeSync` / `writevSync`), falling back to the async method if the
1651+
sync path returns `false` or throws. Similarly, `_final()` tries `endSync()`
1652+
before `end()`. When the sync path succeeds, the callback is deferred via
1653+
`queueMicrotask` to preserve the async resolution contract.
1654+
1655+
The Writable's `highWaterMark` is set to `Number.MAX_SAFE_INTEGER` to
1656+
effectively disable its internal buffering, allowing the underlying Writer
1657+
to manage backpressure directly.
1658+
1659+
```mjs
1660+
import { push, toWritable } from'node:stream/iter';
1661+
1662+
const { writer, readable } =push();
1663+
constwritable=toWritable(writer);
1664+
1665+
writable.write('hello');
1666+
writable.end();
1667+
```
1668+
1669+
```cjs
1670+
const { push, toWritable } =require('node:stream/iter');
1671+
1672+
const { writer, readable } =push();
1673+
constwritable=toWritable(writer);
1674+
1675+
writable.write('hello');
1676+
writable.end();
1677+
```
1678+
14271679
## Protocol symbols
14281680

14291681
These well-known symbols allow third-party objects to participate in the
@@ -1816,10 +2068,15 @@ console.log(textSync(stream)); // 'hello world'
18162068
[`arrayBuffer()`]: #arraybuffersource-options
18172069
[`bytes()`]: #bytessource-options
18182070
[`from()`]: #frominput
2071+
[`fromSync()`]: #fromsyncinput
18192072
[`node:zlib/iter`]: zlib_iter.md
18202073
[`node:zlib/iter` documentation]: zlib_iter.md
18212074
[`pipeTo()`]: #pipetosource-transforms-writer-options
18222075
[`pull()`]: #pullsource-transforms-options
2076+
[`pullSync()`]: #pullsyncsource-transforms-options
18232077
[`share()`]: #sharesource-options
2078+
[`stream.Readable`]: stream.md#class-streamreadable
2079+
[`stream.Writable`]: stream.md#class-streamwritable
18242080
[`tap()`]: #tapcallback
18252081
[`text()`]: #textsource-options
2082+
[`toAsyncStreamable`]: #streamtoasyncstreamable

‎lib/internal/errors.js‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1775,6 +1775,8 @@ E('ERR_STREAM_ALREADY_FINISHED',
17751775
Error);
17761776
E('ERR_STREAM_CANNOT_PIPE','Cannot pipe, not readable',Error);
17771777
E('ERR_STREAM_DESTROYED','Cannot call %s after a stream was destroyed',Error);
1778+
E('ERR_STREAM_ITER_MISSING_FLAG',
1779+
'The stream/iter API requires the --experimental-stream-iter flag',TypeError);
17781780
E('ERR_STREAM_NULL_VALUES','May not write null values to stream',TypeError);
17791781
E('ERR_STREAM_PREMATURE_CLOSE','Premature close',Error);
17801782
E('ERR_STREAM_PUSH_AFTER_EOF','stream.push() after EOF',Error);

0 commit comments

Comments
 (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content

Commit baf98fa

Browse files
jasnelladuh95
authored andcommitted
stream: add stream/iter to classic stream adapters
Signed-off-by: James M Snell <jasnell@gmail.com> Assisted-by: Opencode/Opus 4.6 PR-URL: #62469 Backport-PR-URL: #64675 Reviewed-By: Robert Nagy <ronagy@icloud.com>
1 parent a290f51 commit baf98fa

17 files changed

Lines changed: 3848 additions & 14 deletions

‎doc/api/errors.md‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2906,6 +2906,13 @@ An attempt was made to call [`stream.pipe()`][] on a [`Writable`][] stream.
29062906
A stream method was called that cannot complete because the stream was
29072907
destroyed using `stream.destroy()`.
29082908

2909+
<aid="ERR_STREAM_ITER_MISSING_FLAG"></a>
2910+
2911+
### `ERR_STREAM_ITER_MISSING_FLAG`
2912+
2913+
A stream/iter API was used without the `--experimental-stream-iter` CLI flag
2914+
enabled.
2915+
29092916
<aid="ERR_STREAM_NULL_VALUES"></a>
29102917

29112918
### `ERR_STREAM_NULL_VALUES`

‎doc/api/stream.md‎

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1998,6 +1998,61 @@ option. In the code example above, data will be in a single chunk if the file
19981998
has less then 64 KiB of data because no `highWaterMark` option is provided to
19991999
[`fs.createReadStream()`][].
20002000

2001+
##### `readable[Symbol.for('Stream.toAsyncStreamable')]()`
2002+
2003+
<!-- YAML
2004+
added: REPLACEME
2005+
-->
2006+
2007+
> Stability: 1 - Experimental
2008+
2009+
* Returns: {AsyncIterable} An `AsyncIterable<Uint8Array[]>` that yields
2010+
batched chunks from the stream.
2011+
2012+
When the `--experimental-stream-iter` flag is enabled, `Readable` streams
2013+
implement the [`Stream.toAsyncStreamable`][] protocol, enabling efficient
2014+
consumption by the [`stream/iter`][] API.
2015+
2016+
This provides a batched async iterator that drains the stream's internal
2017+
buffer into `Uint8Array[]` batches, amortizing the per-chunk Promise overhead
2018+
of the standard `Symbol.asyncIterator` path. For byte-mode streams, chunks
2019+
are yielded directly as `Buffer` instances (which are `Uint8Array` subclasses).
2020+
For object-mode or encoded streams, each chunk is normalized to `Uint8Array`
2021+
before batching.
2022+
2023+
The returned iterator is tagged as a validated source, so [`from()`][stream-iter-from]
2024+
passes it through without additional normalization.
2025+
2026+
```mjs
2027+
import { Readable } from'node:stream';
2028+
import { text, from } from'node:stream/iter';
2029+
2030+
constreadable=newReadable({
2031+
read() { this.push('hello'); this.push(null); },
2032+
});
2033+
2034+
// Readable is automatically consumed via toAsyncStreamable
2035+
console.log(awaittext(from(readable))); // 'hello'
2036+
```
2037+
2038+
```cjs
2039+
const { Readable } =require('node:stream');
2040+
const { text, from } =require('node:stream/iter');
2041+
2042+
asyncfunctionrun() {
2043+
constreadable=newReadable({
2044+
read() { this.push('hello'); this.push(null); },
2045+
});
2046+
2047+
console.log(awaittext(from(readable))); // 'hello'
2048+
}
2049+
2050+
run().catch(console.error);
2051+
```
2052+
2053+
Without the `--experimental-stream-iter` flag, calling this method throws
2054+
[`ERR_STREAM_ITER_MISSING_FLAG`][].
2055+
20012056
##### `readable[Symbol.asyncDispose]()`
20022057

20032058
<!-- YAML
@@ -4974,8 +5029,10 @@ contain multi-byte characters.
49745029
[`'finish'`]: #event-finish
49755030
[`'readable'`]: #event-readable
49765031
[`Duplex`]: #class-streamduplex
5032+
[`ERR_STREAM_ITER_MISSING_FLAG`]: errors.md#err_stream_iter_missing_flag
49775033
[`EventEmitter`]: events.md#class-eventemitter
49785034
[`Readable`]: #class-streamreadable
5035+
[`Stream.toAsyncStreamable`]: stream_iter.md#streamtoasyncstreamable
49795036
[`Symbol.hasInstance`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/hasInstance
49805037
[`Transform`]: #class-streamtransform
49815038
[`Writable`]: #class-streamwritable
@@ -5001,6 +5058,7 @@ contain multi-byte characters.
50015058
[`stream.uncork()`]: #writableuncork
50025059
[`stream.unpipe()`]: #readableunpipedestination
50035060
[`stream.wrap()`]: #readablewrapstream
5061+
[`stream/iter`]: stream_iter.md
50045062
[`writable._final()`]: #writable_finalcallback
50055063
[`writable._write()`]: #writable_writechunk-encoding-callback
50065064
[`writable._writev()`]: #writable_writevchunks-callback
@@ -5029,6 +5087,7 @@ contain multi-byte characters.
50295087
[stream-end]: #writableendchunk-encoding-callback
50305088
[stream-finished]: #streamfinishedstream-options-callback
50315089
[stream-finished-promise]: #streamfinishedstream-options
5090+
[stream-iter-from]: stream_iter.md#frominput
50325091
[stream-pause]: #readablepause
50335092
[stream-pipeline]: #streampipelinesource-transforms-destination-callback
50345093
[stream-pipeline-promise]: #streampipelinesource-transforms-destination-options

‎doc/api/stream_iter.md‎

Lines changed: 257 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1424,6 +1424,258 @@ Compression and decompression transforms for use with `pull()`, `pullSync()`,
14241424
`pipeTo()`, and `pipeToSync()` are available via the [`node:zlib/iter`][]
14251425
module. See the [`node:zlib/iter` documentation][] for details.
14261426

1427+
## Classic stream interop
1428+
1429+
These utility functions bridge between classic
1430+
[`stream.Readable`][]/[`stream.Writable`][] streams and the `stream/iter`
1431+
API.
1432+
1433+
Both `fromReadable()` and `fromWritable()` accept duck-typed objects -- they
1434+
do not require the input to extend `stream.Readable` or `stream.Writable`
1435+
directly. The minimum contract is described below for each function.
1436+
1437+
### `fromReadable(readable)`
1438+
1439+
<!-- YAML
1440+
added: REPLACEME
1441+
-->
1442+
1443+
> Stability: 1 - Experimental
1444+
1445+
*`readable` {stream.Readable|Object} A classic Readable stream or any object
1446+
with `read()` and `on()` methods.
1447+
* Returns: {AsyncIterable\<Uint8Array\[]>} A stream/iter async iterable source.
1448+
1449+
Converts a classic Readable stream (or duck-typed equivalent) into a
1450+
stream/iter async iterable source that can be passed to [`from()`][],
1451+
[`pull()`][], [`text()`][], etc.
1452+
1453+
If the object implements the [`toAsyncStreamable`][] protocol (as
1454+
`stream.Readable` does), that protocol is used. Otherwise, the function
1455+
duck-types on `read()` and `on()` (EventEmitter) and wraps the stream with
1456+
a batched async iterator.
1457+
1458+
The result is cached per instance -- calling `fromReadable()` twice with the
1459+
same stream returns the same iterable.
1460+
1461+
For object-mode or encoded Readable streams, chunks are automatically
1462+
normalized to `Uint8Array`.
1463+
1464+
```mjs
1465+
import { Readable } from'node:stream';
1466+
import { fromReadable, text } from'node:stream/iter';
1467+
1468+
constreadable=newReadable({
1469+
read() { this.push('hello world'); this.push(null); },
1470+
});
1471+
1472+
constresult=awaittext(fromReadable(readable));
1473+
console.log(result); // 'hello world'
1474+
```
1475+
1476+
```cjs
1477+
const { Readable } =require('node:stream');
1478+
const { fromReadable, text } =require('node:stream/iter');
1479+
1480+
constreadable=newReadable({
1481+
read() { this.push('hello world'); this.push(null); },
1482+
});
1483+
1484+
asyncfunctionrun() {
1485+
constresult=awaittext(fromReadable(readable));
1486+
console.log(result); // 'hello world'
1487+
}
1488+
run();
1489+
```
1490+
1491+
### `fromWritable(writable[, options])`
1492+
1493+
<!-- YAML
1494+
added: REPLACEME
1495+
-->
1496+
1497+
> Stability: 1 - Experimental
1498+
1499+
*`writable` {stream.Writable|Object} A classic Writable stream or any object
1500+
with `write()` and `on()` methods.
1501+
*`options` {Object}
1502+
*`backpressure` {string} Backpressure policy. **Default:**`'strict'`.
1503+
*`'strict'` -- writes are rejected when the buffer is full. Catches
1504+
callers that ignore backpressure.
1505+
*`'block'` -- writes wait for drain when the buffer is full. Recommended
1506+
for use with [`pipeTo()`][].
1507+
*`'drop-newest'` -- writes are silently discarded when the buffer is full.
1508+
*`'drop-oldest'` -- **not supported**. Throws `ERR_INVALID_ARG_VALUE`.
1509+
* Returns: {Object} A stream/iter Writer adapter.
1510+
1511+
Creates a stream/iter Writer adapter from a classic Writable stream (or
1512+
duck-typed equivalent). The adapter can be passed to [`pipeTo()`][] as a
1513+
destination.
1514+
1515+
Since all writes on a classic Writable are fundamentally asynchronous,
1516+
the synchronous Writer methods (`writeSync`, `writevSync`, `endSync`) always
1517+
return `false` or `-1`, deferring to the async path. The per-write
1518+
`options.signal` parameter from the Writer interface is also ignored.
1519+
1520+
The result is cached per instance -- calling `fromWritable()` twice with the
1521+
same stream returns the same Writer.
1522+
1523+
For duck-typed streams that do not expose `writableHighWaterMark`,
1524+
`writableLength`, or similar properties, sensible defaults are used.
1525+
Object-mode writables (if detectable) are rejected since the Writer
1526+
interface is bytes-only.
1527+
1528+
```mjs
1529+
import { Writable } from'node:stream';
1530+
import { from, fromWritable, pipeTo } from'node:stream/iter';
1531+
1532+
constwritable=newWritable({
1533+
write(chunk, encoding, cb) { console.log(chunk.toString()); cb(); },
1534+
});
1535+
1536+
awaitpipeTo(from('hello world'),
1537+
fromWritable(writable, { backpressure:'block' }));
1538+
```
1539+
1540+
```cjs
1541+
const { Writable } =require('node:stream');
1542+
const { from, fromWritable, pipeTo } =require('node:stream/iter');
1543+
1544+
asyncfunctionrun() {
1545+
constwritable=newWritable({
1546+
write(chunk, encoding, cb) { console.log(chunk.toString()); cb(); },
1547+
});
1548+
1549+
awaitpipeTo(from('hello world'),
1550+
fromWritable(writable, { backpressure:'block' }));
1551+
}
1552+
run();
1553+
```
1554+
1555+
### `toReadable(source[, options])`
1556+
1557+
<!-- YAML
1558+
added: REPLACEME
1559+
-->
1560+
1561+
> Stability: 1 - Experimental
1562+
1563+
*`source` {AsyncIterable} An `AsyncIterable<Uint8Array[]>` source, such as
1564+
the return value of [`pull()`][] or [`from()`][].
1565+
*`options` {Object}
1566+
*`highWaterMark` {number} The internal buffer size in bytes before
1567+
backpressure is applied. **Default:**`65536` (64 KB).
1568+
*`signal` {AbortSignal} An optional signal to abort the readable.
1569+
* Returns: {stream.Readable}
1570+
1571+
Creates a byte-mode [`stream.Readable`][] from an `AsyncIterable<Uint8Array[]>`
1572+
(the native batch format used by the stream/iter API). Each `Uint8Array` in a
1573+
yielded batch is pushed as a separate chunk into the Readable.
1574+
1575+
```mjs
1576+
import { createWriteStream } from'node:fs';
1577+
import { from, pull, toReadable } from'node:stream/iter';
1578+
import { compressGzip } from'node:zlib/iter';
1579+
1580+
constsource=pull(from('hello world'), compressGzip());
1581+
constreadable=toReadable(source);
1582+
1583+
readable.pipe(createWriteStream('output.gz'));
1584+
```
1585+
1586+
```cjs
1587+
const { createWriteStream } =require('node:fs');
1588+
const { from, pull, toReadable } =require('node:stream/iter');
1589+
const { compressGzip } =require('node:zlib/iter');
1590+
1591+
constsource=pull(from('hello world'), compressGzip());
1592+
constreadable=toReadable(source);
1593+
1594+
readable.pipe(createWriteStream('output.gz'));
1595+
```
1596+
1597+
### `toReadableSync(source[, options])`
1598+
1599+
<!-- YAML
1600+
added: REPLACEME
1601+
-->
1602+
1603+
> Stability: 1 - Experimental
1604+
1605+
*`source` {Iterable} An `Iterable<Uint8Array[]>` source, such as the
1606+
return value of [`pullSync()`][] or [`fromSync()`][].
1607+
*`options` {Object}
1608+
*`highWaterMark` {number} The internal buffer size in bytes before
1609+
backpressure is applied. **Default:**`65536` (64 KB).
1610+
* Returns: {stream.Readable}
1611+
1612+
Creates a byte-mode [`stream.Readable`][] from a synchronous
1613+
`Iterable<Uint8Array[]>`. The `_read()` method pulls from the iterator
1614+
synchronously, so data is available immediately via `readable.read()`.
1615+
1616+
```mjs
1617+
import { fromSync, toReadableSync } from'node:stream/iter';
1618+
1619+
constsource=fromSync('hello world');
1620+
constreadable=toReadableSync(source);
1621+
1622+
console.log(readable.read().toString()); // 'hello world'
1623+
```
1624+
1625+
```cjs
1626+
const { fromSync, toReadableSync } =require('node:stream/iter');
1627+
1628+
constsource=fromSync('hello world');
1629+
constreadable=toReadableSync(source);
1630+
1631+
console.log(readable.read().toString()); // 'hello world'
1632+
```
1633+
1634+
### `toWritable(writer)`
1635+
1636+
<!-- YAML
1637+
added: REPLACEME
1638+
-->
1639+
1640+
> Stability: 1 - Experimental
1641+
1642+
*`writer` {Object} A stream/iter Writer. Only the `write()` method is
1643+
required; `end()`, `fail()`, `writeSync()`, `writevSync()`, `endSync()`,
1644+
and `writev()` are optional.
1645+
* Returns: {stream.Writable}
1646+
1647+
Creates a classic [`stream.Writable`][] backed by a stream/iter Writer.
1648+
1649+
Each `_write()` / `_writev()` call attempts the Writer's synchronous method
1650+
first (`writeSync` / `writevSync`), falling back to the async method if the
1651+
sync path returns `false` or throws. Similarly, `_final()` tries `endSync()`
1652+
before `end()`. When the sync path succeeds, the callback is deferred via
1653+
`queueMicrotask` to preserve the async resolution contract.
1654+
1655+
The Writable's `highWaterMark` is set to `Number.MAX_SAFE_INTEGER` to
1656+
effectively disable its internal buffering, allowing the underlying Writer
1657+
to manage backpressure directly.
1658+
1659+
```mjs
1660+
import { push, toWritable } from'node:stream/iter';
1661+
1662+
const { writer, readable } =push();
1663+
constwritable=toWritable(writer);
1664+
1665+
writable.write('hello');
1666+
writable.end();
1667+
```
1668+
1669+
```cjs
1670+
const { push, toWritable } =require('node:stream/iter');
1671+
1672+
const { writer, readable } =push();
1673+
constwritable=toWritable(writer);
1674+
1675+
writable.write('hello');
1676+
writable.end();
1677+
```
1678+
14271679
## Protocol symbols
14281680

14291681
These well-known symbols allow third-party objects to participate in the
@@ -1816,10 +2068,15 @@ console.log(textSync(stream)); // 'hello world'
18162068
[`arrayBuffer()`]: #arraybuffersource-options
18172069
[`bytes()`]: #bytessource-options
18182070
[`from()`]: #frominput
2071+
[`fromSync()`]: #fromsyncinput
18192072
[`node:zlib/iter`]: zlib_iter.md
18202073
[`node:zlib/iter` documentation]: zlib_iter.md
18212074
[`pipeTo()`]: #pipetosource-transforms-writer-options
18222075
[`pull()`]: #pullsource-transforms-options
2076+
[`pullSync()`]: #pullsyncsource-transforms-options
18232077
[`share()`]: #sharesource-options
2078+
[`stream.Readable`]: stream.md#class-streamreadable
2079+
[`stream.Writable`]: stream.md#class-streamwritable
18242080
[`tap()`]: #tapcallback
18252081
[`text()`]: #textsource-options
2082+
[`toAsyncStreamable`]: #streamtoasyncstreamable

‎lib/internal/errors.js‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1775,6 +1775,8 @@ E('ERR_STREAM_ALREADY_FINISHED',
17751775
Error);
17761776
E('ERR_STREAM_CANNOT_PIPE','Cannot pipe, not readable',Error);
17771777
E('ERR_STREAM_DESTROYED','Cannot call %s after a stream was destroyed',Error);
1778+
E('ERR_STREAM_ITER_MISSING_FLAG',
1779+
'The stream/iter API requires the --experimental-stream-iter flag',TypeError);
17781780
E('ERR_STREAM_NULL_VALUES','May not write null values to stream',TypeError);
17791781
E('ERR_STREAM_PREMATURE_CLOSE','Premature close',Error);
17801782
E('ERR_STREAM_PUSH_AFTER_EOF','stream.push() after EOF',Error);

0 commit comments

Comments
 (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Commit baf98fa

Browse files
jasnelladuh95
authored andcommitted
stream: add stream/iter to classic stream adapters
Signed-off-by: James M Snell <jasnell@gmail.com> Assisted-by: Opencode/Opus 4.6 PR-URL: #62469 Backport-PR-URL: #64675 Reviewed-By: Robert Nagy <ronagy@icloud.com>
1 parent a290f51 commit baf98fa

17 files changed

Lines changed: 3848 additions & 14 deletions

‎doc/api/errors.md‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2906,6 +2906,13 @@ An attempt was made to call [`stream.pipe()`][] on a [`Writable`][] stream.
29062906
A stream method was called that cannot complete because the stream was
29072907
destroyed using `stream.destroy()`.
29082908

2909+
<aid="ERR_STREAM_ITER_MISSING_FLAG"></a>
2910+
2911+
### `ERR_STREAM_ITER_MISSING_FLAG`
2912+
2913+
A stream/iter API was used without the `--experimental-stream-iter` CLI flag
2914+
enabled.
2915+
29092916
<aid="ERR_STREAM_NULL_VALUES"></a>
29102917

29112918
### `ERR_STREAM_NULL_VALUES`

‎doc/api/stream.md‎

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1998,6 +1998,61 @@ option. In the code example above, data will be in a single chunk if the file
19981998
has less then 64 KiB of data because no `highWaterMark` option is provided to
19991999
[`fs.createReadStream()`][].
20002000

2001+
##### `readable[Symbol.for('Stream.toAsyncStreamable')]()`
2002+
2003+
<!-- YAML
2004+
added: REPLACEME
2005+
-->
2006+
2007+
> Stability: 1 - Experimental
2008+
2009+
* Returns: {AsyncIterable} An `AsyncIterable<Uint8Array[]>` that yields
2010+
batched chunks from the stream.
2011+
2012+
When the `--experimental-stream-iter` flag is enabled, `Readable` streams
2013+
implement the [`Stream.toAsyncStreamable`][] protocol, enabling efficient
2014+
consumption by the [`stream/iter`][] API.
2015+
2016+
This provides a batched async iterator that drains the stream's internal
2017+
buffer into `Uint8Array[]` batches, amortizing the per-chunk Promise overhead
2018+
of the standard `Symbol.asyncIterator` path. For byte-mode streams, chunks
2019+
are yielded directly as `Buffer` instances (which are `Uint8Array` subclasses).
2020+
For object-mode or encoded streams, each chunk is normalized to `Uint8Array`
2021+
before batching.
2022+
2023+
The returned iterator is tagged as a validated source, so [`from()`][stream-iter-from]
2024+
passes it through without additional normalization.
2025+
2026+
```mjs
2027+
import { Readable } from'node:stream';
2028+
import { text, from } from'node:stream/iter';
2029+
2030+
constreadable=newReadable({
2031+
read() { this.push('hello'); this.push(null); },
2032+
});
2033+
2034+
// Readable is automatically consumed via toAsyncStreamable
2035+
console.log(awaittext(from(readable))); // 'hello'
2036+
```
2037+
2038+
```cjs
2039+
const { Readable } =require('node:stream');
2040+
const { text, from } =require('node:stream/iter');
2041+
2042+
asyncfunctionrun() {
2043+
constreadable=newReadable({
2044+
read() { this.push('hello'); this.push(null); },
2045+
});
2046+
2047+
console.log(awaittext(from(readable))); // 'hello'
2048+
}
2049+
2050+
run().catch(console.error);
2051+
```
2052+
2053+
Without the `--experimental-stream-iter` flag, calling this method throws
2054+
[`ERR_STREAM_ITER_MISSING_FLAG`][].
2055+
20012056
##### `readable[Symbol.asyncDispose]()`
20022057

20032058
<!-- YAML
@@ -4974,8 +5029,10 @@ contain multi-byte characters.
49745029
[`'finish'`]: #event-finish
49755030
[`'readable'`]: #event-readable
49765031
[`Duplex`]: #class-streamduplex
5032+
[`ERR_STREAM_ITER_MISSING_FLAG`]: errors.md#err_stream_iter_missing_flag
49775033
[`EventEmitter`]: events.md#class-eventemitter
49785034
[`Readable`]: #class-streamreadable
5035+
[`Stream.toAsyncStreamable`]: stream_iter.md#streamtoasyncstreamable
49795036
[`Symbol.hasInstance`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/hasInstance
49805037
[`Transform`]: #class-streamtransform
49815038
[`Writable`]: #class-streamwritable
@@ -5001,6 +5058,7 @@ contain multi-byte characters.
50015058
[`stream.uncork()`]: #writableuncork
50025059
[`stream.unpipe()`]: #readableunpipedestination
50035060
[`stream.wrap()`]: #readablewrapstream
5061+
[`stream/iter`]: stream_iter.md
50045062
[`writable._final()`]: #writable_finalcallback
50055063
[`writable._write()`]: #writable_writechunk-encoding-callback
50065064
[`writable._writev()`]: #writable_writevchunks-callback
@@ -5029,6 +5087,7 @@ contain multi-byte characters.
50295087
[stream-end]: #writableendchunk-encoding-callback
50305088
[stream-finished]: #streamfinishedstream-options-callback
50315089
[stream-finished-promise]: #streamfinishedstream-options
5090+
[stream-iter-from]: stream_iter.md#frominput
50325091
[stream-pause]: #readablepause
50335092
[stream-pipeline]: #streampipelinesource-transforms-destination-callback
50345093
[stream-pipeline-promise]: #streampipelinesource-transforms-destination-options

‎doc/api/stream_iter.md‎

Lines changed: 257 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1424,6 +1424,258 @@ Compression and decompression transforms for use with `pull()`, `pullSync()`,
14241424
`pipeTo()`, and `pipeToSync()` are available via the [`node:zlib/iter`][]
14251425
module. See the [`node:zlib/iter` documentation][] for details.
14261426

1427+
## Classic stream interop
1428+
1429+
These utility functions bridge between classic
1430+
[`stream.Readable`][]/[`stream.Writable`][] streams and the `stream/iter`
1431+
API.
1432+
1433+
Both `fromReadable()` and `fromWritable()` accept duck-typed objects -- they
1434+
do not require the input to extend `stream.Readable` or `stream.Writable`
1435+
directly. The minimum contract is described below for each function.
1436+
1437+
### `fromReadable(readable)`
1438+
1439+
<!-- YAML
1440+
added: REPLACEME
1441+
-->
1442+
1443+
> Stability: 1 - Experimental
1444+
1445+
*`readable` {stream.Readable|Object} A classic Readable stream or any object
1446+
with `read()` and `on()` methods.
1447+
* Returns: {AsyncIterable\<Uint8Array\[]>} A stream/iter async iterable source.
1448+
1449+
Converts a classic Readable stream (or duck-typed equivalent) into a
1450+
stream/iter async iterable source that can be passed to [`from()`][],
1451+
[`pull()`][], [`text()`][], etc.
1452+
1453+
If the object implements the [`toAsyncStreamable`][] protocol (as
1454+
`stream.Readable` does), that protocol is used. Otherwise, the function
1455+
duck-types on `read()` and `on()` (EventEmitter) and wraps the stream with
1456+
a batched async iterator.
1457+
1458+
The result is cached per instance -- calling `fromReadable()` twice with the
1459+
same stream returns the same iterable.
1460+
1461+
For object-mode or encoded Readable streams, chunks are automatically
1462+
normalized to `Uint8Array`.
1463+
1464+
```mjs
1465+
import { Readable } from'node:stream';
1466+
import { fromReadable, text } from'node:stream/iter';
1467+
1468+
constreadable=newReadable({
1469+
read() { this.push('hello world'); this.push(null); },
1470+
});
1471+
1472+
constresult=awaittext(fromReadable(readable));
1473+
console.log(result); // 'hello world'
1474+
```
1475+
1476+
```cjs
1477+
const { Readable } =require('node:stream');
1478+
const { fromReadable, text } =require('node:stream/iter');
1479+
1480+
constreadable=newReadable({
1481+
read() { this.push('hello world'); this.push(null); },
1482+
});
1483+
1484+
asyncfunctionrun() {
1485+
constresult=awaittext(fromReadable(readable));
1486+
console.log(result); // 'hello world'
1487+
}
1488+
run();
1489+
```
1490+
1491+
### `fromWritable(writable[, options])`
1492+
1493+
<!-- YAML
1494+
added: REPLACEME
1495+
-->
1496+
1497+
> Stability: 1 - Experimental
1498+
1499+
*`writable` {stream.Writable|Object} A classic Writable stream or any object
1500+
with `write()` and `on()` methods.
1501+
*`options` {Object}
1502+
*`backpressure` {string} Backpressure policy. **Default:**`'strict'`.
1503+
*`'strict'` -- writes are rejected when the buffer is full. Catches
1504+
callers that ignore backpressure.
1505+
*`'block'` -- writes wait for drain when the buffer is full. Recommended
1506+
for use with [`pipeTo()`][].
1507+
*`'drop-newest'` -- writes are silently discarded when the buffer is full.
1508+
*`'drop-oldest'` -- **not supported**. Throws `ERR_INVALID_ARG_VALUE`.
1509+
* Returns: {Object} A stream/iter Writer adapter.
1510+
1511+
Creates a stream/iter Writer adapter from a classic Writable stream (or
1512+
duck-typed equivalent). The adapter can be passed to [`pipeTo()`][] as a
1513+
destination.
1514+
1515+
Since all writes on a classic Writable are fundamentally asynchronous,
1516+
the synchronous Writer methods (`writeSync`, `writevSync`, `endSync`) always
1517+
return `false` or `-1`, deferring to the async path. The per-write
1518+
`options.signal` parameter from the Writer interface is also ignored.
1519+
1520+
The result is cached per instance -- calling `fromWritable()` twice with the
1521+
same stream returns the same Writer.
1522+
1523+
For duck-typed streams that do not expose `writableHighWaterMark`,
1524+
`writableLength`, or similar properties, sensible defaults are used.
1525+
Object-mode writables (if detectable) are rejected since the Writer
1526+
interface is bytes-only.
1527+
1528+
```mjs
1529+
import { Writable } from'node:stream';
1530+
import { from, fromWritable, pipeTo } from'node:stream/iter';
1531+
1532+
constwritable=newWritable({
1533+
write(chunk, encoding, cb) { console.log(chunk.toString()); cb(); },
1534+
});
1535+
1536+
awaitpipeTo(from('hello world'),
1537+
fromWritable(writable, { backpressure:'block' }));
1538+
```
1539+
1540+
```cjs
1541+
const { Writable } =require('node:stream');
1542+
const { from, fromWritable, pipeTo } =require('node:stream/iter');
1543+
1544+
asyncfunctionrun() {
1545+
constwritable=newWritable({
1546+
write(chunk, encoding, cb) { console.log(chunk.toString()); cb(); },
1547+
});
1548+
1549+
awaitpipeTo(from('hello world'),
1550+
fromWritable(writable, { backpressure:'block' }));
1551+
}
1552+
run();
1553+
```
1554+
1555+
### `toReadable(source[, options])`
1556+
1557+
<!-- YAML
1558+
added: REPLACEME
1559+
-->
1560+
1561+
> Stability: 1 - Experimental
1562+
1563+
*`source` {AsyncIterable} An `AsyncIterable<Uint8Array[]>` source, such as
1564+
the return value of [`pull()`][] or [`from()`][].
1565+
*`options` {Object}
1566+
*`highWaterMark` {number} The internal buffer size in bytes before
1567+
backpressure is applied. **Default:**`65536` (64 KB).
1568+
*`signal` {AbortSignal} An optional signal to abort the readable.
1569+
* Returns: {stream.Readable}
1570+
1571+
Creates a byte-mode [`stream.Readable`][] from an `AsyncIterable<Uint8Array[]>`
1572+
(the native batch format used by the stream/iter API). Each `Uint8Array` in a
1573+
yielded batch is pushed as a separate chunk into the Readable.
1574+
1575+
```mjs
1576+
import { createWriteStream } from'node:fs';
1577+
import { from, pull, toReadable } from'node:stream/iter';
1578+
import { compressGzip } from'node:zlib/iter';
1579+
1580+
constsource=pull(from('hello world'), compressGzip());
1581+
constreadable=toReadable(source);
1582+
1583+
readable.pipe(createWriteStream('output.gz'));
1584+
```
1585+
1586+
```cjs
1587+
const { createWriteStream } =require('node:fs');
1588+
const { from, pull, toReadable } =require('node:stream/iter');
1589+
const { compressGzip } =require('node:zlib/iter');
1590+
1591+
constsource=pull(from('hello world'), compressGzip());
1592+
constreadable=toReadable(source);
1593+
1594+
readable.pipe(createWriteStream('output.gz'));
1595+
```
1596+
1597+
### `toReadableSync(source[, options])`
1598+
1599+
<!-- YAML
1600+
added: REPLACEME
1601+
-->
1602+
1603+
> Stability: 1 - Experimental
1604+
1605+
*`source` {Iterable} An `Iterable<Uint8Array[]>` source, such as the
1606+
return value of [`pullSync()`][] or [`fromSync()`][].
1607+
*`options` {Object}
1608+
*`highWaterMark` {number} The internal buffer size in bytes before
1609+
backpressure is applied. **Default:**`65536` (64 KB).
1610+
* Returns: {stream.Readable}
1611+
1612+
Creates a byte-mode [`stream.Readable`][] from a synchronous
1613+
`Iterable<Uint8Array[]>`. The `_read()` method pulls from the iterator
1614+
synchronously, so data is available immediately via `readable.read()`.
1615+
1616+
```mjs
1617+
import { fromSync, toReadableSync } from'node:stream/iter';
1618+
1619+
constsource=fromSync('hello world');
1620+
constreadable=toReadableSync(source);
1621+
1622+
console.log(readable.read().toString()); // 'hello world'
1623+
```
1624+
1625+
```cjs
1626+
const { fromSync, toReadableSync } =require('node:stream/iter');
1627+
1628+
constsource=fromSync('hello world');
1629+
constreadable=toReadableSync(source);
1630+
1631+
console.log(readable.read().toString()); // 'hello world'
1632+
```
1633+
1634+
### `toWritable(writer)`
1635+
1636+
<!-- YAML
1637+
added: REPLACEME
1638+
-->
1639+
1640+
> Stability: 1 - Experimental
1641+
1642+
*`writer` {Object} A stream/iter Writer. Only the `write()` method is
1643+
required; `end()`, `fail()`, `writeSync()`, `writevSync()`, `endSync()`,
1644+
and `writev()` are optional.
1645+
* Returns: {stream.Writable}
1646+
1647+
Creates a classic [`stream.Writable`][] backed by a stream/iter Writer.
1648+
1649+
Each `_write()` / `_writev()` call attempts the Writer's synchronous method
1650+
first (`writeSync` / `writevSync`), falling back to the async method if the
1651+
sync path returns `false` or throws. Similarly, `_final()` tries `endSync()`
1652+
before `end()`. When the sync path succeeds, the callback is deferred via
1653+
`queueMicrotask` to preserve the async resolution contract.
1654+
1655+
The Writable's `highWaterMark` is set to `Number.MAX_SAFE_INTEGER` to
1656+
effectively disable its internal buffering, allowing the underlying Writer
1657+
to manage backpressure directly.
1658+
1659+
```mjs
1660+
import { push, toWritable } from'node:stream/iter';
1661+
1662+
const { writer, readable } =push();
1663+
constwritable=toWritable(writer);
1664+
1665+
writable.write('hello');
1666+
writable.end();
1667+
```
1668+
1669+
```cjs
1670+
const { push, toWritable } =require('node:stream/iter');
1671+
1672+
const { writer, readable } =push();
1673+
constwritable=toWritable(writer);
1674+
1675+
writable.write('hello');
1676+
writable.end();
1677+
```
1678+
14271679
## Protocol symbols
14281680

14291681
These well-known symbols allow third-party objects to participate in the
@@ -1816,10 +2068,15 @@ console.log(textSync(stream)); // 'hello world'
18162068
[`arrayBuffer()`]: #arraybuffersource-options
18172069
[`bytes()`]: #bytessource-options
18182070
[`from()`]: #frominput
2071+
[`fromSync()`]: #fromsyncinput
18192072
[`node:zlib/iter`]: zlib_iter.md
18202073
[`node:zlib/iter` documentation]: zlib_iter.md
18212074
[`pipeTo()`]: #pipetosource-transforms-writer-options
18222075
[`pull()`]: #pullsource-transforms-options
2076+
[`pullSync()`]: #pullsyncsource-transforms-options
18232077
[`share()`]: #sharesource-options
2078+
[`stream.Readable`]: stream.md#class-streamreadable
2079+
[`stream.Writable`]: stream.md#class-streamwritable
18242080
[`tap()`]: #tapcallback
18252081
[`text()`]: #textsource-options
2082+
[`toAsyncStreamable`]: #streamtoasyncstreamable

‎lib/internal/errors.js‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1775,6 +1775,8 @@ E('ERR_STREAM_ALREADY_FINISHED',
17751775
Error);
17761776
E('ERR_STREAM_CANNOT_PIPE','Cannot pipe, not readable',Error);
17771777
E('ERR_STREAM_DESTROYED','Cannot call %s after a stream was destroyed',Error);
1778+
E('ERR_STREAM_ITER_MISSING_FLAG',
1779+
'The stream/iter API requires the --experimental-stream-iter flag',TypeError);
17781780
E('ERR_STREAM_NULL_VALUES','May not write null values to stream',TypeError);
17791781
E('ERR_STREAM_PREMATURE_CLOSE','Premature close',Error);
17801782
E('ERR_STREAM_PUSH_AFTER_EOF','stream.push() after EOF',Error);

0 commit comments

Comments
 (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Commit baf98fa

Browse files
jasnelladuh95
authored andcommitted
stream: add stream/iter to classic stream adapters
Signed-off-by: James M Snell <jasnell@gmail.com> Assisted-by: Opencode/Opus 4.6 PR-URL: #62469 Backport-PR-URL: #64675 Reviewed-By: Robert Nagy <ronagy@icloud.com>
1 parent a290f51 commit baf98fa

17 files changed

Lines changed: 3848 additions & 14 deletions

‎doc/api/errors.md‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2906,6 +2906,13 @@ An attempt was made to call [`stream.pipe()`][] on a [`Writable`][] stream.
29062906
A stream method was called that cannot complete because the stream was
29072907
destroyed using `stream.destroy()`.
29082908

2909+
<aid="ERR_STREAM_ITER_MISSING_FLAG"></a>
2910+
2911+
### `ERR_STREAM_ITER_MISSING_FLAG`
2912+
2913+
A stream/iter API was used without the `--experimental-stream-iter` CLI flag
2914+
enabled.
2915+
29092916
<aid="ERR_STREAM_NULL_VALUES"></a>
29102917

29112918
### `ERR_STREAM_NULL_VALUES`

‎doc/api/stream.md‎

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1998,6 +1998,61 @@ option. In the code example above, data will be in a single chunk if the file
19981998
has less then 64 KiB of data because no `highWaterMark` option is provided to
19991999
[`fs.createReadStream()`][].
20002000

2001+
##### `readable[Symbol.for('Stream.toAsyncStreamable')]()`
2002+
2003+
<!-- YAML
2004+
added: REPLACEME
2005+
-->
2006+
2007+
> Stability: 1 - Experimental
2008+
2009+
* Returns: {AsyncIterable} An `AsyncIterable<Uint8Array[]>` that yields
2010+
batched chunks from the stream.
2011+
2012+
When the `--experimental-stream-iter` flag is enabled, `Readable` streams
2013+
implement the [`Stream.toAsyncStreamable`][] protocol, enabling efficient
2014+
consumption by the [`stream/iter`][] API.
2015+
2016+
This provides a batched async iterator that drains the stream's internal
2017+
buffer into `Uint8Array[]` batches, amortizing the per-chunk Promise overhead
2018+
of the standard `Symbol.asyncIterator` path. For byte-mode streams, chunks
2019+
are yielded directly as `Buffer` instances (which are `Uint8Array` subclasses).
2020+
For object-mode or encoded streams, each chunk is normalized to `Uint8Array`
2021+
before batching.
2022+
2023+
The returned iterator is tagged as a validated source, so [`from()`][stream-iter-from]
2024+
passes it through without additional normalization.
2025+
2026+
```mjs
2027+
import { Readable } from'node:stream';
2028+
import { text, from } from'node:stream/iter';
2029+
2030+
constreadable=newReadable({
2031+
read() { this.push('hello'); this.push(null); },
2032+
});
2033+
2034+
// Readable is automatically consumed via toAsyncStreamable
2035+
console.log(awaittext(from(readable))); // 'hello'
2036+
```
2037+
2038+
```cjs
2039+
const { Readable } =require('node:stream');
2040+
const { text, from } =require('node:stream/iter');
2041+
2042+
asyncfunctionrun() {
2043+
constreadable=newReadable({
2044+
read() { this.push('hello'); this.push(null); },
2045+
});
2046+
2047+
console.log(awaittext(from(readable))); // 'hello'
2048+
}
2049+
2050+
run().catch(console.error);
2051+
```
2052+
2053+
Without the `--experimental-stream-iter` flag, calling this method throws
2054+
[`ERR_STREAM_ITER_MISSING_FLAG`][].
2055+
20012056
##### `readable[Symbol.asyncDispose]()`
20022057

20032058
<!-- YAML
@@ -4974,8 +5029,10 @@ contain multi-byte characters.
49745029
[`'finish'`]: #event-finish
49755030
[`'readable'`]: #event-readable
49765031
[`Duplex`]: #class-streamduplex
5032+
[`ERR_STREAM_ITER_MISSING_FLAG`]: errors.md#err_stream_iter_missing_flag
49775033
[`EventEmitter`]: events.md#class-eventemitter
49785034
[`Readable`]: #class-streamreadable
5035+
[`Stream.toAsyncStreamable`]: stream_iter.md#streamtoasyncstreamable
49795036
[`Symbol.hasInstance`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/hasInstance
49805037
[`Transform`]: #class-streamtransform
49815038
[`Writable`]: #class-streamwritable
@@ -5001,6 +5058,7 @@ contain multi-byte characters.
50015058
[`stream.uncork()`]: #writableuncork
50025059
[`stream.unpipe()`]: #readableunpipedestination
50035060
[`stream.wrap()`]: #readablewrapstream
5061+
[`stream/iter`]: stream_iter.md
50045062
[`writable._final()`]: #writable_finalcallback
50055063
[`writable._write()`]: #writable_writechunk-encoding-callback
50065064
[`writable._writev()`]: #writable_writevchunks-callback
@@ -5029,6 +5087,7 @@ contain multi-byte characters.
50295087
[stream-end]: #writableendchunk-encoding-callback
50305088
[stream-finished]: #streamfinishedstream-options-callback
50315089
[stream-finished-promise]: #streamfinishedstream-options
5090+
[stream-iter-from]: stream_iter.md#frominput
50325091
[stream-pause]: #readablepause
50335092
[stream-pipeline]: #streampipelinesource-transforms-destination-callback
50345093
[stream-pipeline-promise]: #streampipelinesource-transforms-destination-options

‎doc/api/stream_iter.md‎

Lines changed: 257 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1424,6 +1424,258 @@ Compression and decompression transforms for use with `pull()`, `pullSync()`,
14241424
`pipeTo()`, and `pipeToSync()` are available via the [`node:zlib/iter`][]
14251425
module. See the [`node:zlib/iter` documentation][] for details.
14261426

1427+
## Classic stream interop
1428+
1429+
These utility functions bridge between classic
1430+
[`stream.Readable`][]/[`stream.Writable`][] streams and the `stream/iter`
1431+
API.
1432+
1433+
Both `fromReadable()` and `fromWritable()` accept duck-typed objects -- they
1434+
do not require the input to extend `stream.Readable` or `stream.Writable`
1435+
directly. The minimum contract is described below for each function.
1436+
1437+
### `fromReadable(readable)`
1438+
1439+
<!-- YAML
1440+
added: REPLACEME
1441+
-->
1442+
1443+
> Stability: 1 - Experimental
1444+
1445+
*`readable` {stream.Readable|Object} A classic Readable stream or any object
1446+
with `read()` and `on()` methods.
1447+
* Returns: {AsyncIterable\<Uint8Array\[]>} A stream/iter async iterable source.
1448+
1449+
Converts a classic Readable stream (or duck-typed equivalent) into a
1450+
stream/iter async iterable source that can be passed to [`from()`][],
1451+
[`pull()`][], [`text()`][], etc.
1452+
1453+
If the object implements the [`toAsyncStreamable`][] protocol (as
1454+
`stream.Readable` does), that protocol is used. Otherwise, the function
1455+
duck-types on `read()` and `on()` (EventEmitter) and wraps the stream with
1456+
a batched async iterator.
1457+
1458+
The result is cached per instance -- calling `fromReadable()` twice with the
1459+
same stream returns the same iterable.
1460+
1461+
For object-mode or encoded Readable streams, chunks are automatically
1462+
normalized to `Uint8Array`.
1463+
1464+
```mjs
1465+
import { Readable } from'node:stream';
1466+
import { fromReadable, text } from'node:stream/iter';
1467+
1468+
constreadable=newReadable({
1469+
read() { this.push('hello world'); this.push(null); },
1470+
});
1471+
1472+
constresult=awaittext(fromReadable(readable));
1473+
console.log(result); // 'hello world'
1474+
```
1475+
1476+
```cjs
1477+
const { Readable } =require('node:stream');
1478+
const { fromReadable, text } =require('node:stream/iter');
1479+
1480+
constreadable=newReadable({
1481+
read() { this.push('hello world'); this.push(null); },
1482+
});
1483+
1484+
asyncfunctionrun() {
1485+
constresult=awaittext(fromReadable(readable));
1486+
console.log(result); // 'hello world'
1487+
}
1488+
run();
1489+
```
1490+
1491+
### `fromWritable(writable[, options])`
1492+
1493+
<!-- YAML
1494+
added: REPLACEME
1495+
-->
1496+
1497+
> Stability: 1 - Experimental
1498+
1499+
*`writable` {stream.Writable|Object} A classic Writable stream or any object
1500+
with `write()` and `on()` methods.
1501+
*`options` {Object}
1502+
*`backpressure` {string} Backpressure policy. **Default:**`'strict'`.
1503+
*`'strict'` -- writes are rejected when the buffer is full. Catches
1504+
callers that ignore backpressure.
1505+
*`'block'` -- writes wait for drain when the buffer is full. Recommended
1506+
for use with [`pipeTo()`][].
1507+
*`'drop-newest'` -- writes are silently discarded when the buffer is full.
1508+
*`'drop-oldest'` -- **not supported**. Throws `ERR_INVALID_ARG_VALUE`.
1509+
* Returns: {Object} A stream/iter Writer adapter.
1510+
1511+
Creates a stream/iter Writer adapter from a classic Writable stream (or
1512+
duck-typed equivalent). The adapter can be passed to [`pipeTo()`][] as a
1513+
destination.
1514+
1515+
Since all writes on a classic Writable are fundamentally asynchronous,
1516+
the synchronous Writer methods (`writeSync`, `writevSync`, `endSync`) always
1517+
return `false` or `-1`, deferring to the async path. The per-write
1518+
`options.signal` parameter from the Writer interface is also ignored.
1519+
1520+
The result is cached per instance -- calling `fromWritable()` twice with the
1521+
same stream returns the same Writer.
1522+
1523+
For duck-typed streams that do not expose `writableHighWaterMark`,
1524+
`writableLength`, or similar properties, sensible defaults are used.
1525+
Object-mode writables (if detectable) are rejected since the Writer
1526+
interface is bytes-only.
1527+
1528+
```mjs
1529+
import { Writable } from'node:stream';
1530+
import { from, fromWritable, pipeTo } from'node:stream/iter';
1531+
1532+
constwritable=newWritable({
1533+
write(chunk, encoding, cb) { console.log(chunk.toString()); cb(); },
1534+
});
1535+
1536+
awaitpipeTo(from('hello world'),
1537+
fromWritable(writable, { backpressure:'block' }));
1538+
```
1539+
1540+
```cjs
1541+
const { Writable } =require('node:stream');
1542+
const { from, fromWritable, pipeTo } =require('node:stream/iter');
1543+
1544+
asyncfunctionrun() {
1545+
constwritable=newWritable({
1546+
write(chunk, encoding, cb) { console.log(chunk.toString()); cb(); },
1547+
});
1548+
1549+
awaitpipeTo(from('hello world'),
1550+
fromWritable(writable, { backpressure:'block' }));
1551+
}
1552+
run();
1553+
```
1554+
1555+
### `toReadable(source[, options])`
1556+
1557+
<!-- YAML
1558+
added: REPLACEME
1559+
-->
1560+
1561+
> Stability: 1 - Experimental
1562+
1563+
*`source` {AsyncIterable} An `AsyncIterable<Uint8Array[]>` source, such as
1564+
the return value of [`pull()`][] or [`from()`][].
1565+
*`options` {Object}
1566+
*`highWaterMark` {number} The internal buffer size in bytes before
1567+
backpressure is applied. **Default:**`65536` (64 KB).
1568+
*`signal` {AbortSignal} An optional signal to abort the readable.
1569+
* Returns: {stream.Readable}
1570+
1571+
Creates a byte-mode [`stream.Readable`][] from an `AsyncIterable<Uint8Array[]>`
1572+
(the native batch format used by the stream/iter API). Each `Uint8Array` in a
1573+
yielded batch is pushed as a separate chunk into the Readable.
1574+
1575+
```mjs
1576+
import { createWriteStream } from'node:fs';
1577+
import { from, pull, toReadable } from'node:stream/iter';
1578+
import { compressGzip } from'node:zlib/iter';
1579+
1580+
constsource=pull(from('hello world'), compressGzip());
1581+
constreadable=toReadable(source);
1582+
1583+
readable.pipe(createWriteStream('output.gz'));
1584+
```
1585+
1586+
```cjs
1587+
const { createWriteStream } =require('node:fs');
1588+
const { from, pull, toReadable } =require('node:stream/iter');
1589+
const { compressGzip } =require('node:zlib/iter');
1590+
1591+
constsource=pull(from('hello world'), compressGzip());
1592+
constreadable=toReadable(source);
1593+
1594+
readable.pipe(createWriteStream('output.gz'));
1595+
```
1596+
1597+
### `toReadableSync(source[, options])`
1598+
1599+
<!-- YAML
1600+
added: REPLACEME
1601+
-->
1602+
1603+
> Stability: 1 - Experimental
1604+
1605+
*`source` {Iterable} An `Iterable<Uint8Array[]>` source, such as the
1606+
return value of [`pullSync()`][] or [`fromSync()`][].
1607+
*`options` {Object}
1608+
*`highWaterMark` {number} The internal buffer size in bytes before
1609+
backpressure is applied. **Default:**`65536` (64 KB).
1610+
* Returns: {stream.Readable}
1611+
1612+
Creates a byte-mode [`stream.Readable`][] from a synchronous
1613+
`Iterable<Uint8Array[]>`. The `_read()` method pulls from the iterator
1614+
synchronously, so data is available immediately via `readable.read()`.
1615+
1616+
```mjs
1617+
import { fromSync, toReadableSync } from'node:stream/iter';
1618+
1619+
constsource=fromSync('hello world');
1620+
constreadable=toReadableSync(source);
1621+
1622+
console.log(readable.read().toString()); // 'hello world'
1623+
```
1624+
1625+
```cjs
1626+
const { fromSync, toReadableSync } =require('node:stream/iter');
1627+
1628+
constsource=fromSync('hello world');
1629+
constreadable=toReadableSync(source);
1630+
1631+
console.log(readable.read().toString()); // 'hello world'
1632+
```
1633+
1634+
### `toWritable(writer)`
1635+
1636+
<!-- YAML
1637+
added: REPLACEME
1638+
-->
1639+
1640+
> Stability: 1 - Experimental
1641+
1642+
*`writer` {Object} A stream/iter Writer. Only the `write()` method is
1643+
required; `end()`, `fail()`, `writeSync()`, `writevSync()`, `endSync()`,
1644+
and `writev()` are optional.
1645+
* Returns: {stream.Writable}
1646+
1647+
Creates a classic [`stream.Writable`][] backed by a stream/iter Writer.
1648+
1649+
Each `_write()` / `_writev()` call attempts the Writer's synchronous method
1650+
first (`writeSync` / `writevSync`), falling back to the async method if the
1651+
sync path returns `false` or throws. Similarly, `_final()` tries `endSync()`
1652+
before `end()`. When the sync path succeeds, the callback is deferred via
1653+
`queueMicrotask` to preserve the async resolution contract.
1654+
1655+
The Writable's `highWaterMark` is set to `Number.MAX_SAFE_INTEGER` to
1656+
effectively disable its internal buffering, allowing the underlying Writer
1657+
to manage backpressure directly.
1658+
1659+
```mjs
1660+
import { push, toWritable } from'node:stream/iter';
1661+
1662+
const { writer, readable } =push();
1663+
constwritable=toWritable(writer);
1664+
1665+
writable.write('hello');
1666+
writable.end();
1667+
```
1668+
1669+
```cjs
1670+
const { push, toWritable } =require('node:stream/iter');
1671+
1672+
const { writer, readable } =push();
1673+
constwritable=toWritable(writer);
1674+
1675+
writable.write('hello');
1676+
writable.end();
1677+
```
1678+
14271679
## Protocol symbols
14281680

14291681
These well-known symbols allow third-party objects to participate in the
@@ -1816,10 +2068,15 @@ console.log(textSync(stream)); // 'hello world'
18162068
[`arrayBuffer()`]: #arraybuffersource-options
18172069
[`bytes()`]: #bytessource-options
18182070
[`from()`]: #frominput
2071+
[`fromSync()`]: #fromsyncinput
18192072
[`node:zlib/iter`]: zlib_iter.md
18202073
[`node:zlib/iter` documentation]: zlib_iter.md
18212074
[`pipeTo()`]: #pipetosource-transforms-writer-options
18222075
[`pull()`]: #pullsource-transforms-options
2076+
[`pullSync()`]: #pullsyncsource-transforms-options
18232077
[`share()`]: #sharesource-options
2078+
[`stream.Readable`]: stream.md#class-streamreadable
2079+
[`stream.Writable`]: stream.md#class-streamwritable
18242080
[`tap()`]: #tapcallback
18252081
[`text()`]: #textsource-options
2082+
[`toAsyncStreamable`]: #streamtoasyncstreamable

‎lib/internal/errors.js‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1775,6 +1775,8 @@ E('ERR_STREAM_ALREADY_FINISHED',
17751775
Error);
17761776
E('ERR_STREAM_CANNOT_PIPE','Cannot pipe, not readable',Error);
17771777
E('ERR_STREAM_DESTROYED','Cannot call %s after a stream was destroyed',Error);
1778+
E('ERR_STREAM_ITER_MISSING_FLAG',
1779+
'The stream/iter API requires the --experimental-stream-iter flag',TypeError);
17781780
E('ERR_STREAM_NULL_VALUES','May not write null values to stream',TypeError);
17791781
E('ERR_STREAM_PREMATURE_CLOSE','Premature close',Error);
17801782
E('ERR_STREAM_PUSH_AFTER_EOF','stream.push() after EOF',Error);

0 commit comments

Comments
 (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content

Commit baf98fa

Browse files
jasnelladuh95
authored andcommitted
stream: add stream/iter to classic stream adapters
Signed-off-by: James M Snell <jasnell@gmail.com> Assisted-by: Opencode/Opus 4.6 PR-URL: #62469 Backport-PR-URL: #64675 Reviewed-By: Robert Nagy <ronagy@icloud.com>
1 parent a290f51 commit baf98fa

17 files changed

Lines changed: 3848 additions & 14 deletions

‎doc/api/errors.md‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2906,6 +2906,13 @@ An attempt was made to call [`stream.pipe()`][] on a [`Writable`][] stream.
29062906
A stream method was called that cannot complete because the stream was
29072907
destroyed using `stream.destroy()`.
29082908

2909+
<aid="ERR_STREAM_ITER_MISSING_FLAG"></a>
2910+
2911+
### `ERR_STREAM_ITER_MISSING_FLAG`
2912+
2913+
A stream/iter API was used without the `--experimental-stream-iter` CLI flag
2914+
enabled.
2915+
29092916
<aid="ERR_STREAM_NULL_VALUES"></a>
29102917

29112918
### `ERR_STREAM_NULL_VALUES`

‎doc/api/stream.md‎

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1998,6 +1998,61 @@ option. In the code example above, data will be in a single chunk if the file
19981998
has less then 64 KiB of data because no `highWaterMark` option is provided to
19991999
[`fs.createReadStream()`][].
20002000

2001+
##### `readable[Symbol.for('Stream.toAsyncStreamable')]()`
2002+
2003+
<!-- YAML
2004+
added: REPLACEME
2005+
-->
2006+
2007+
> Stability: 1 - Experimental
2008+
2009+
* Returns: {AsyncIterable} An `AsyncIterable<Uint8Array[]>` that yields
2010+
batched chunks from the stream.
2011+
2012+
When the `--experimental-stream-iter` flag is enabled, `Readable` streams
2013+
implement the [`Stream.toAsyncStreamable`][] protocol, enabling efficient
2014+
consumption by the [`stream/iter`][] API.
2015+
2016+
This provides a batched async iterator that drains the stream's internal
2017+
buffer into `Uint8Array[]` batches, amortizing the per-chunk Promise overhead
2018+
of the standard `Symbol.asyncIterator` path. For byte-mode streams, chunks
2019+
are yielded directly as `Buffer` instances (which are `Uint8Array` subclasses).
2020+
For object-mode or encoded streams, each chunk is normalized to `Uint8Array`
2021+
before batching.
2022+
2023+
The returned iterator is tagged as a validated source, so [`from()`][stream-iter-from]
2024+
passes it through without additional normalization.
2025+
2026+
```mjs
2027+
import { Readable } from'node:stream';
2028+
import { text, from } from'node:stream/iter';
2029+
2030+
constreadable=newReadable({
2031+
read() { this.push('hello'); this.push(null); },
2032+
});
2033+
2034+
// Readable is automatically consumed via toAsyncStreamable
2035+
console.log(awaittext(from(readable))); // 'hello'
2036+
```
2037+
2038+
```cjs
2039+
const { Readable } =require('node:stream');
2040+
const { text, from } =require('node:stream/iter');
2041+
2042+
asyncfunctionrun() {
2043+
constreadable=newReadable({
2044+
read() { this.push('hello'); this.push(null); },
2045+
});
2046+
2047+
console.log(awaittext(from(readable))); // 'hello'
2048+
}
2049+
2050+
run().catch(console.error);
2051+
```
2052+
2053+
Without the `--experimental-stream-iter` flag, calling this method throws
2054+
[`ERR_STREAM_ITER_MISSING_FLAG`][].
2055+
20012056
##### `readable[Symbol.asyncDispose]()`
20022057

20032058
<!-- YAML
@@ -4974,8 +5029,10 @@ contain multi-byte characters.
49745029
[`'finish'`]: #event-finish
49755030
[`'readable'`]: #event-readable
49765031
[`Duplex`]: #class-streamduplex
5032+
[`ERR_STREAM_ITER_MISSING_FLAG`]: errors.md#err_stream_iter_missing_flag
49775033
[`EventEmitter`]: events.md#class-eventemitter
49785034
[`Readable`]: #class-streamreadable
5035+
[`Stream.toAsyncStreamable`]: stream_iter.md#streamtoasyncstreamable
49795036
[`Symbol.hasInstance`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/hasInstance
49805037
[`Transform`]: #class-streamtransform
49815038
[`Writable`]: #class-streamwritable
@@ -5001,6 +5058,7 @@ contain multi-byte characters.
50015058
[`stream.uncork()`]: #writableuncork
50025059
[`stream.unpipe()`]: #readableunpipedestination
50035060
[`stream.wrap()`]: #readablewrapstream
5061+
[`stream/iter`]: stream_iter.md
50045062
[`writable._final()`]: #writable_finalcallback
50055063
[`writable._write()`]: #writable_writechunk-encoding-callback
50065064
[`writable._writev()`]: #writable_writevchunks-callback
@@ -5029,6 +5087,7 @@ contain multi-byte characters.
50295087
[stream-end]: #writableendchunk-encoding-callback
50305088
[stream-finished]: #streamfinishedstream-options-callback
50315089
[stream-finished-promise]: #streamfinishedstream-options
5090+
[stream-iter-from]: stream_iter.md#frominput
50325091
[stream-pause]: #readablepause
50335092
[stream-pipeline]: #streampipelinesource-transforms-destination-callback
50345093
[stream-pipeline-promise]: #streampipelinesource-transforms-destination-options

‎doc/api/stream_iter.md‎

Lines changed: 257 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1424,6 +1424,258 @@ Compression and decompression transforms for use with `pull()`, `pullSync()`,
14241424
`pipeTo()`, and `pipeToSync()` are available via the [`node:zlib/iter`][]
14251425
module. See the [`node:zlib/iter` documentation][] for details.
14261426

1427+
## Classic stream interop
1428+
1429+
These utility functions bridge between classic
1430+
[`stream.Readable`][]/[`stream.Writable`][] streams and the `stream/iter`
1431+
API.
1432+
1433+
Both `fromReadable()` and `fromWritable()` accept duck-typed objects -- they
1434+
do not require the input to extend `stream.Readable` or `stream.Writable`
1435+
directly. The minimum contract is described below for each function.
1436+
1437+
### `fromReadable(readable)`
1438+
1439+
<!-- YAML
1440+
added: REPLACEME
1441+
-->
1442+
1443+
> Stability: 1 - Experimental
1444+
1445+
*`readable` {stream.Readable|Object} A classic Readable stream or any object
1446+
with `read()` and `on()` methods.
1447+
* Returns: {AsyncIterable\<Uint8Array\[]>} A stream/iter async iterable source.
1448+
1449+
Converts a classic Readable stream (or duck-typed equivalent) into a
1450+
stream/iter async iterable source that can be passed to [`from()`][],
1451+
[`pull()`][], [`text()`][], etc.
1452+
1453+
If the object implements the [`toAsyncStreamable`][] protocol (as
1454+
`stream.Readable` does), that protocol is used. Otherwise, the function
1455+
duck-types on `read()` and `on()` (EventEmitter) and wraps the stream with
1456+
a batched async iterator.
1457+
1458+
The result is cached per instance -- calling `fromReadable()` twice with the
1459+
same stream returns the same iterable.
1460+
1461+
For object-mode or encoded Readable streams, chunks are automatically
1462+
normalized to `Uint8Array`.
1463+
1464+
```mjs
1465+
import { Readable } from'node:stream';
1466+
import { fromReadable, text } from'node:stream/iter';
1467+
1468+
constreadable=newReadable({
1469+
read() { this.push('hello world'); this.push(null); },
1470+
});
1471+
1472+
constresult=awaittext(fromReadable(readable));
1473+
console.log(result); // 'hello world'
1474+
```
1475+
1476+
```cjs
1477+
const { Readable } =require('node:stream');
1478+
const { fromReadable, text } =require('node:stream/iter');
1479+
1480+
constreadable=newReadable({
1481+
read() { this.push('hello world'); this.push(null); },
1482+
});
1483+
1484+
asyncfunctionrun() {
1485+
constresult=awaittext(fromReadable(readable));
1486+
console.log(result); // 'hello world'
1487+
}
1488+
run();
1489+
```
1490+
1491+
### `fromWritable(writable[, options])`
1492+
1493+
<!-- YAML
1494+
added: REPLACEME
1495+
-->
1496+
1497+
> Stability: 1 - Experimental
1498+
1499+
*`writable` {stream.Writable|Object} A classic Writable stream or any object
1500+
with `write()` and `on()` methods.
1501+
*`options` {Object}
1502+
*`backpressure` {string} Backpressure policy. **Default:**`'strict'`.
1503+
*`'strict'` -- writes are rejected when the buffer is full. Catches
1504+
callers that ignore backpressure.
1505+
*`'block'` -- writes wait for drain when the buffer is full. Recommended
1506+
for use with [`pipeTo()`][].
1507+
*`'drop-newest'` -- writes are silently discarded when the buffer is full.
1508+
*`'drop-oldest'` -- **not supported**. Throws `ERR_INVALID_ARG_VALUE`.
1509+
* Returns: {Object} A stream/iter Writer adapter.
1510+
1511+
Creates a stream/iter Writer adapter from a classic Writable stream (or
1512+
duck-typed equivalent). The adapter can be passed to [`pipeTo()`][] as a
1513+
destination.
1514+
1515+
Since all writes on a classic Writable are fundamentally asynchronous,
1516+
the synchronous Writer methods (`writeSync`, `writevSync`, `endSync`) always
1517+
return `false` or `-1`, deferring to the async path. The per-write
1518+
`options.signal` parameter from the Writer interface is also ignored.
1519+
1520+
The result is cached per instance -- calling `fromWritable()` twice with the
1521+
same stream returns the same Writer.
1522+
1523+
For duck-typed streams that do not expose `writableHighWaterMark`,
1524+
`writableLength`, or similar properties, sensible defaults are used.
1525+
Object-mode writables (if detectable) are rejected since the Writer
1526+
interface is bytes-only.
1527+
1528+
```mjs
1529+
import { Writable } from'node:stream';
1530+
import { from, fromWritable, pipeTo } from'node:stream/iter';
1531+
1532+
constwritable=newWritable({
1533+
write(chunk, encoding, cb) { console.log(chunk.toString()); cb(); },
1534+
});
1535+
1536+
awaitpipeTo(from('hello world'),
1537+
fromWritable(writable, { backpressure:'block' }));
1538+
```
1539+
1540+
```cjs
1541+
const { Writable } =require('node:stream');
1542+
const { from, fromWritable, pipeTo } =require('node:stream/iter');
1543+
1544+
asyncfunctionrun() {
1545+
constwritable=newWritable({
1546+
write(chunk, encoding, cb) { console.log(chunk.toString()); cb(); },
1547+
});
1548+
1549+
awaitpipeTo(from('hello world'),
1550+
fromWritable(writable, { backpressure:'block' }));
1551+
}
1552+
run();
1553+
```
1554+
1555+
### `toReadable(source[, options])`
1556+
1557+
<!-- YAML
1558+
added: REPLACEME
1559+
-->
1560+
1561+
> Stability: 1 - Experimental
1562+
1563+
*`source` {AsyncIterable} An `AsyncIterable<Uint8Array[]>` source, such as
1564+
the return value of [`pull()`][] or [`from()`][].
1565+
*`options` {Object}
1566+
*`highWaterMark` {number} The internal buffer size in bytes before
1567+
backpressure is applied. **Default:**`65536` (64 KB).
1568+
*`signal` {AbortSignal} An optional signal to abort the readable.
1569+
* Returns: {stream.Readable}
1570+
1571+
Creates a byte-mode [`stream.Readable`][] from an `AsyncIterable<Uint8Array[]>`
1572+
(the native batch format used by the stream/iter API). Each `Uint8Array` in a
1573+
yielded batch is pushed as a separate chunk into the Readable.
1574+
1575+
```mjs
1576+
import { createWriteStream } from'node:fs';
1577+
import { from, pull, toReadable } from'node:stream/iter';
1578+
import { compressGzip } from'node:zlib/iter';
1579+
1580+
constsource=pull(from('hello world'), compressGzip());
1581+
constreadable=toReadable(source);
1582+
1583+
readable.pipe(createWriteStream('output.gz'));
1584+
```
1585+
1586+
```cjs
1587+
const { createWriteStream } =require('node:fs');
1588+
const { from, pull, toReadable } =require('node:stream/iter');
1589+
const { compressGzip } =require('node:zlib/iter');
1590+
1591+
constsource=pull(from('hello world'), compressGzip());
1592+
constreadable=toReadable(source);
1593+
1594+
readable.pipe(createWriteStream('output.gz'));
1595+
```
1596+
1597+
### `toReadableSync(source[, options])`
1598+
1599+
<!-- YAML
1600+
added: REPLACEME
1601+
-->
1602+
1603+
> Stability: 1 - Experimental
1604+
1605+
*`source` {Iterable} An `Iterable<Uint8Array[]>` source, such as the
1606+
return value of [`pullSync()`][] or [`fromSync()`][].
1607+
*`options` {Object}
1608+
*`highWaterMark` {number} The internal buffer size in bytes before
1609+
backpressure is applied. **Default:**`65536` (64 KB).
1610+
* Returns: {stream.Readable}
1611+
1612+
Creates a byte-mode [`stream.Readable`][] from a synchronous
1613+
`Iterable<Uint8Array[]>`. The `_read()` method pulls from the iterator
1614+
synchronously, so data is available immediately via `readable.read()`.
1615+
1616+
```mjs
1617+
import { fromSync, toReadableSync } from'node:stream/iter';
1618+
1619+
constsource=fromSync('hello world');
1620+
constreadable=toReadableSync(source);
1621+
1622+
console.log(readable.read().toString()); // 'hello world'
1623+
```
1624+
1625+
```cjs
1626+
const { fromSync, toReadableSync } =require('node:stream/iter');
1627+
1628+
constsource=fromSync('hello world');
1629+
constreadable=toReadableSync(source);
1630+
1631+
console.log(readable.read().toString()); // 'hello world'
1632+
```
1633+
1634+
### `toWritable(writer)`
1635+
1636+
<!-- YAML
1637+
added: REPLACEME
1638+
-->
1639+
1640+
> Stability: 1 - Experimental
1641+
1642+
*`writer` {Object} A stream/iter Writer. Only the `write()` method is
1643+
required; `end()`, `fail()`, `writeSync()`, `writevSync()`, `endSync()`,
1644+
and `writev()` are optional.
1645+
* Returns: {stream.Writable}
1646+
1647+
Creates a classic [`stream.Writable`][] backed by a stream/iter Writer.
1648+
1649+
Each `_write()` / `_writev()` call attempts the Writer's synchronous method
1650+
first (`writeSync` / `writevSync`), falling back to the async method if the
1651+
sync path returns `false` or throws. Similarly, `_final()` tries `endSync()`
1652+
before `end()`. When the sync path succeeds, the callback is deferred via
1653+
`queueMicrotask` to preserve the async resolution contract.
1654+
1655+
The Writable's `highWaterMark` is set to `Number.MAX_SAFE_INTEGER` to
1656+
effectively disable its internal buffering, allowing the underlying Writer
1657+
to manage backpressure directly.
1658+
1659+
```mjs
1660+
import { push, toWritable } from'node:stream/iter';
1661+
1662+
const { writer, readable } =push();
1663+
constwritable=toWritable(writer);
1664+
1665+
writable.write('hello');
1666+
writable.end();
1667+
```
1668+
1669+
```cjs
1670+
const { push, toWritable } =require('node:stream/iter');
1671+
1672+
const { writer, readable } =push();
1673+
constwritable=toWritable(writer);
1674+
1675+
writable.write('hello');
1676+
writable.end();
1677+
```
1678+
14271679
## Protocol symbols
14281680

14291681
These well-known symbols allow third-party objects to participate in the
@@ -1816,10 +2068,15 @@ console.log(textSync(stream)); // 'hello world'
18162068
[`arrayBuffer()`]: #arraybuffersource-options
18172069
[`bytes()`]: #bytessource-options
18182070
[`from()`]: #frominput
2071+
[`fromSync()`]: #fromsyncinput
18192072
[`node:zlib/iter`]: zlib_iter.md
18202073
[`node:zlib/iter` documentation]: zlib_iter.md
18212074
[`pipeTo()`]: #pipetosource-transforms-writer-options
18222075
[`pull()`]: #pullsource-transforms-options
2076+
[`pullSync()`]: #pullsyncsource-transforms-options
18232077
[`share()`]: #sharesource-options
2078+
[`stream.Readable`]: stream.md#class-streamreadable
2079+
[`stream.Writable`]: stream.md#class-streamwritable
18242080
[`tap()`]: #tapcallback
18252081
[`text()`]: #textsource-options
2082+
[`toAsyncStreamable`]: #streamtoasyncstreamable

‎lib/internal/errors.js‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1775,6 +1775,8 @@ E('ERR_STREAM_ALREADY_FINISHED',
17751775
Error);
17761776
E('ERR_STREAM_CANNOT_PIPE','Cannot pipe, not readable',Error);
17771777
E('ERR_STREAM_DESTROYED','Cannot call %s after a stream was destroyed',Error);
1778+
E('ERR_STREAM_ITER_MISSING_FLAG',
1779+
'The stream/iter API requires the --experimental-stream-iter flag',TypeError);
17781780
E('ERR_STREAM_NULL_VALUES','May not write null values to stream',TypeError);
17791781
E('ERR_STREAM_PREMATURE_CLOSE','Premature close',Error);
17801782
E('ERR_STREAM_PUSH_AFTER_EOF','stream.push() after EOF',Error);

0 commit comments

Comments
 (0)