@@ -45,8 +45,8 @@ There are four fundamental stream types within Node.js:
4545 is written and read (for example, [`zlib.createDeflate()`][]).
4646
4747Additionally, this module includes the utility functions
48- [`stream.pipeline()`][], [`stream.finished()`][] and
49- [`stream.Readable.from ()`][].
48+ [`stream.pipeline()`][], [`stream.finished()`][], [`stream.Readable.from()`][]
49+ and [`stream.addAbortSignal ()`][].
5050
5151### Streams Promises API
5252<!-- YAML
@@ -1799,6 +1799,55 @@ Calling `Readable.from(string)` or `Readable.from(buffer)` will not have
17991799the strings or buffers be iterated to match the other streams semantics
18001800for performance reasons.
18011801
1802+ ### `stream.addAbortSignal(signal, stream)`
1803+ <!-- YAML
1804+ added: REPLACEME
1805+ -->
1806+ * `signal` {AbortSignal} A signal representing possible cancellation
1807+ * `stream` {Stream} a stream to attach a signal to
1808+
1809+ Attaches an AbortSignal to a readable or writeable stream. This lets code
1810+ control stream destruction using an `AbortController`.
1811+
1812+ Calling `abort` on the `AbortController` corresponding to the passed
1813+ `AbortSignal` will behave the same way as calling `.destroy(new AbortError())`
1814+ on the stream.
1815+
1816+ ```js
1817+ const fs = require('fs');
1818+
1819+ const controller = new AbortController();
1820+ const read = addAbortSignal(
1821+ controller.signal,
1822+ fs.createReadStream(('object.json'))
1823+ );
1824+ // Later, abort the operation closing the stream
1825+ controller.abort();
1826+ ```
1827+
1828+ Or using an `AbortSignal` with a readable stream as an async iterable:
1829+
1830+ ```js
1831+ const controller = new AbortController();
1832+ setTimeout(() => controller.abort(), 10_000); // set a timeout
1833+ const stream = addAbortSignal(
1834+ controller.signal,
1835+ fs.createReadStream(('object.json'))
1836+ );
1837+ (async () => {
1838+ try {
1839+ for await (const chunk of stream) {
1840+ await process(chunk);
1841+ }
1842+ } catch (e) {
1843+ if (e.name === 'AbortError') {
1844+ // The operation was cancelled
1845+ } else {
1846+ throw e;
1847+ }
1848+ }
1849+ })();
1850+ ```
18021851## API for stream implementers
18031852
18041853<!--type=misc-->
@@ -3123,6 +3172,7 @@ contain multi-byte characters.
31233172[`stream.finished()`]: #stream_stream_finished_stream_options_callback
31243173[`stream.pipe()`]: #stream_readable_pipe_destination_options
31253174[`stream.pipeline()`]: #stream_stream_pipeline_source_transforms_destination_callback
3175+ [`stream.addAbortSignal()`]: #stream_stream_addabortsignal_signal_stream
31263176[`stream.uncork()`]: #stream_writable_uncork
31273177[`stream.unpipe()`]: #stream_readable_unpipe_destination
31283178[`stream.wrap()`]: #stream_readable_wrap_stream
0 commit comments