githrun

A CLI tool to run Python scrip...
Log | Files | Refs | README | LICENSE

stream.d.ts (74430B)


      1 /**
      2  * A stream is an abstract interface for working with streaming data in Node.js.
      3  * The `stream` module provides an API for implementing the stream interface.
      4  *
      5  * There are many stream objects provided by Node.js. For instance, a `request to an HTTP server` and `process.stdout` are both stream instances.
      6  *
      7  * Streams can be readable, writable, or both. All streams are instances of `EventEmitter`.
      8  *
      9  * To access the `stream` module:
     10  *
     11  * ```js
     12  * import stream from 'node:stream';
     13  * ```
     14  *
     15  * The `stream` module is useful for creating new types of stream instances. It is
     16  * usually not necessary to use the `stream` module to consume streams.
     17  * @see [source](https://github.com/nodejs/node/blob/v16.9.0/lib/stream.js)
     18  */
     19 declare module "stream" {
     20     import { Abortable, EventEmitter } from "node:events";
     21     import { Blob as NodeBlob } from "node:buffer";
     22     import * as streamPromises from "node:stream/promises";
     23     import * as streamConsumers from "node:stream/consumers";
     24     class internal extends EventEmitter {
     25         pipe<T extends NodeJS.WritableStream>(
     26             destination: T,
     27             options?: {
     28                 end?: boolean | undefined;
     29             },
     30         ): T;
     31     }
     32     namespace internal {
     33         class Stream extends internal {
     34             constructor(opts?: ReadableOptions);
     35         }
     36         interface StreamOptions<T extends Stream> extends Abortable {
     37             emitClose?: boolean | undefined;
     38             highWaterMark?: number | undefined;
     39             objectMode?: boolean | undefined;
     40             construct?(this: T, callback: (error?: Error | null) => void): void;
     41             destroy?(this: T, error: Error | null, callback: (error?: Error | null) => void): void;
     42             autoDestroy?: boolean | undefined;
     43         }
     44         interface ReadableOptions extends StreamOptions<Readable> {
     45             encoding?: BufferEncoding | undefined;
     46             read?(this: Readable, size: number): void;
     47         }
     48         interface ArrayOptions {
     49             /** the maximum concurrent invocations of `fn` to call on the stream at once. **Default: 1**. */
     50             concurrency?: number;
     51             /** allows destroying the stream if the signal is aborted. */
     52             signal?: AbortSignal;
     53         }
     54         /**
     55          * @since v0.9.4
     56          */
     57         class Readable extends Stream implements NodeJS.ReadableStream {
     58             /**
     59              * A utility method for creating Readable Streams out of iterators.
     60              */
     61             static from(iterable: Iterable<any> | AsyncIterable<any>, options?: ReadableOptions): Readable;
     62             /**
     63              * Returns whether the stream has been read from or cancelled.
     64              * @since v16.8.0
     65              */
     66             static isDisturbed(stream: Readable | NodeJS.ReadableStream): boolean;
     67             /**
     68              * Returns whether the stream was destroyed or errored before emitting `'end'`.
     69              * @since v16.8.0
     70              * @experimental
     71              */
     72             readonly readableAborted: boolean;
     73             /**
     74              * Is `true` if it is safe to call `readable.read()`, which means
     75              * the stream has not been destroyed or emitted `'error'` or `'end'`.
     76              * @since v11.4.0
     77              */
     78             readable: boolean;
     79             /**
     80              * Returns whether `'data'` has been emitted.
     81              * @since v16.7.0
     82              * @experimental
     83              */
     84             readonly readableDidRead: boolean;
     85             /**
     86              * Getter for the property `encoding` of a given `Readable` stream. The `encoding`property can be set using the `readable.setEncoding()` method.
     87              * @since v12.7.0
     88              */
     89             readonly readableEncoding: BufferEncoding | null;
     90             /**
     91              * Becomes `true` when `'end'` event is emitted.
     92              * @since v12.9.0
     93              */
     94             readonly readableEnded: boolean;
     95             /**
     96              * This property reflects the current state of a `Readable` stream as described
     97              * in the `Three states` section.
     98              * @since v9.4.0
     99              */
    100             readonly readableFlowing: boolean | null;
    101             /**
    102              * Returns the value of `highWaterMark` passed when creating this `Readable`.
    103              * @since v9.3.0
    104              */
    105             readonly readableHighWaterMark: number;
    106             /**
    107              * This property contains the number of bytes (or objects) in the queue
    108              * ready to be read. The value provides introspection data regarding
    109              * the status of the `highWaterMark`.
    110              * @since v9.4.0
    111              */
    112             readonly readableLength: number;
    113             /**
    114              * Getter for the property `objectMode` of a given `Readable` stream.
    115              * @since v12.3.0
    116              */
    117             readonly readableObjectMode: boolean;
    118             /**
    119              * Is `true` after `readable.destroy()` has been called.
    120              * @since v8.0.0
    121              */
    122             destroyed: boolean;
    123             constructor(opts?: ReadableOptions);
    124             _construct?(callback: (error?: Error | null) => void): void;
    125             _read(size: number): void;
    126             /**
    127              * The `readable.read()` method pulls some data out of the internal buffer and
    128              * returns it. If no data available to be read, `null` is returned. By default,
    129              * the data will be returned as a `Buffer` object unless an encoding has been
    130              * specified using the `readable.setEncoding()` method or the stream is operating
    131              * in object mode.
    132              *
    133              * The optional `size` argument specifies a specific number of bytes to read. If`size` bytes are not available to be read, `null` will be returned _unless_the stream has ended, in which
    134              * case all of the data remaining in the internal
    135              * buffer will be returned.
    136              *
    137              * If the `size` argument is not specified, all of the data contained in the
    138              * internal buffer will be returned.
    139              *
    140              * The `size` argument must be less than or equal to 1 GiB.
    141              *
    142              * The `readable.read()` method should only be called on `Readable` streams
    143              * operating in paused mode. In flowing mode, `readable.read()` is called
    144              * automatically until the internal buffer is fully drained.
    145              *
    146              * ```js
    147              * const readable = getReadableStreamSomehow();
    148              *
    149              * // 'readable' may be triggered multiple times as data is buffered in
    150              * readable.on('readable', () => {
    151              *   let chunk;
    152              *   console.log('Stream is readable (new data received in buffer)');
    153              *   // Use a loop to make sure we read all currently available data
    154              *   while (null !== (chunk = readable.read())) {
    155              *     console.log(`Read ${chunk.length} bytes of data...`);
    156              *   }
    157              * });
    158              *
    159              * // 'end' will be triggered once when there is no more data available
    160              * readable.on('end', () => {
    161              *   console.log('Reached end of stream.');
    162              * });
    163              * ```
    164              *
    165              * Each call to `readable.read()` returns a chunk of data, or `null`. The chunks
    166              * are not concatenated. A `while` loop is necessary to consume all data
    167              * currently in the buffer. When reading a large file `.read()` may return `null`,
    168              * having consumed all buffered content so far, but there is still more data to
    169              * come not yet buffered. In this case a new `'readable'` event will be emitted
    170              * when there is more data in the buffer. Finally the `'end'` event will be
    171              * emitted when there is no more data to come.
    172              *
    173              * Therefore to read a file's whole contents from a `readable`, it is necessary
    174              * to collect chunks across multiple `'readable'` events:
    175              *
    176              * ```js
    177              * const chunks = [];
    178              *
    179              * readable.on('readable', () => {
    180              *   let chunk;
    181              *   while (null !== (chunk = readable.read())) {
    182              *     chunks.push(chunk);
    183              *   }
    184              * });
    185              *
    186              * readable.on('end', () => {
    187              *   const content = chunks.join('');
    188              * });
    189              * ```
    190              *
    191              * A `Readable` stream in object mode will always return a single item from
    192              * a call to `readable.read(size)`, regardless of the value of the`size` argument.
    193              *
    194              * If the `readable.read()` method returns a chunk of data, a `'data'` event will
    195              * also be emitted.
    196              *
    197              * Calling {@link read} after the `'end'` event has
    198              * been emitted will return `null`. No runtime error will be raised.
    199              * @since v0.9.4
    200              * @param size Optional argument to specify how much data to read.
    201              */
    202             read(size?: number): any;
    203             /**
    204              * The `readable.setEncoding()` method sets the character encoding for
    205              * data read from the `Readable` stream.
    206              *
    207              * By default, no encoding is assigned and stream data will be returned as`Buffer` objects. Setting an encoding causes the stream data
    208              * to be returned as strings of the specified encoding rather than as `Buffer`objects. For instance, calling `readable.setEncoding('utf8')` will cause the
    209              * output data to be interpreted as UTF-8 data, and passed as strings. Calling`readable.setEncoding('hex')` will cause the data to be encoded in hexadecimal
    210              * string format.
    211              *
    212              * The `Readable` stream will properly handle multi-byte characters delivered
    213              * through the stream that would otherwise become improperly decoded if simply
    214              * pulled from the stream as `Buffer` objects.
    215              *
    216              * ```js
    217              * const readable = getReadableStreamSomehow();
    218              * readable.setEncoding('utf8');
    219              * readable.on('data', (chunk) => {
    220              *   assert.equal(typeof chunk, 'string');
    221              *   console.log('Got %d characters of string data:', chunk.length);
    222              * });
    223              * ```
    224              * @since v0.9.4
    225              * @param encoding The encoding to use.
    226              */
    227             setEncoding(encoding: BufferEncoding): this;
    228             /**
    229              * The `readable.pause()` method will cause a stream in flowing mode to stop
    230              * emitting `'data'` events, switching out of flowing mode. Any data that
    231              * becomes available will remain in the internal buffer.
    232              *
    233              * ```js
    234              * const readable = getReadableStreamSomehow();
    235              * readable.on('data', (chunk) => {
    236              *   console.log(`Received ${chunk.length} bytes of data.`);
    237              *   readable.pause();
    238              *   console.log('There will be no additional data for 1 second.');
    239              *   setTimeout(() => {
    240              *     console.log('Now data will start flowing again.');
    241              *     readable.resume();
    242              *   }, 1000);
    243              * });
    244              * ```
    245              *
    246              * The `readable.pause()` method has no effect if there is a `'readable'`event listener.
    247              * @since v0.9.4
    248              */
    249             pause(): this;
    250             /**
    251              * The `readable.resume()` method causes an explicitly paused `Readable` stream to
    252              * resume emitting `'data'` events, switching the stream into flowing mode.
    253              *
    254              * The `readable.resume()` method can be used to fully consume the data from a
    255              * stream without actually processing any of that data:
    256              *
    257              * ```js
    258              * getReadableStreamSomehow()
    259              *   .resume()
    260              *   .on('end', () => {
    261              *     console.log('Reached the end, but did not read anything.');
    262              *   });
    263              * ```
    264              *
    265              * The `readable.resume()` method has no effect if there is a `'readable'`event listener.
    266              * @since v0.9.4
    267              */
    268             resume(): this;
    269             /**
    270              * The `readable.isPaused()` method returns the current operating state of the`Readable`. This is used primarily by the mechanism that underlies the`readable.pipe()` method. In most
    271              * typical cases, there will be no reason to
    272              * use this method directly.
    273              *
    274              * ```js
    275              * const readable = new stream.Readable();
    276              *
    277              * readable.isPaused(); // === false
    278              * readable.pause();
    279              * readable.isPaused(); // === true
    280              * readable.resume();
    281              * readable.isPaused(); // === false
    282              * ```
    283              * @since v0.11.14
    284              */
    285             isPaused(): boolean;
    286             /**
    287              * The `readable.unpipe()` method detaches a `Writable` stream previously attached
    288              * using the {@link pipe} method.
    289              *
    290              * If the `destination` is not specified, then _all_ pipes are detached.
    291              *
    292              * If the `destination` is specified, but no pipe is set up for it, then
    293              * the method does nothing.
    294              *
    295              * ```js
    296              * import fs from 'node:fs';
    297              * const readable = getReadableStreamSomehow();
    298              * const writable = fs.createWriteStream('file.txt');
    299              * // All the data from readable goes into 'file.txt',
    300              * // but only for the first second.
    301              * readable.pipe(writable);
    302              * setTimeout(() => {
    303              *   console.log('Stop writing to file.txt.');
    304              *   readable.unpipe(writable);
    305              *   console.log('Manually close the file stream.');
    306              *   writable.end();
    307              * }, 1000);
    308              * ```
    309              * @since v0.9.4
    310              * @param destination Optional specific stream to unpipe
    311              */
    312             unpipe(destination?: NodeJS.WritableStream): this;
    313             /**
    314              * Passing `chunk` as `null` signals the end of the stream (EOF) and behaves the
    315              * same as `readable.push(null)`, after which no more data can be written. The EOF
    316              * signal is put at the end of the buffer and any buffered data will still be
    317              * flushed.
    318              *
    319              * The `readable.unshift()` method pushes a chunk of data back into the internal
    320              * buffer. This is useful in certain situations where a stream is being consumed by
    321              * code that needs to "un-consume" some amount of data that it has optimistically
    322              * pulled out of the source, so that the data can be passed on to some other party.
    323              *
    324              * The `stream.unshift(chunk)` method cannot be called after the `'end'` event
    325              * has been emitted or a runtime error will be thrown.
    326              *
    327              * Developers using `stream.unshift()` often should consider switching to
    328              * use of a `Transform` stream instead. See the `API for stream implementers` section for more information.
    329              *
    330              * ```js
    331              * // Pull off a header delimited by \n\n.
    332              * // Use unshift() if we get too much.
    333              * // Call the callback with (error, header, stream).
    334              * import { StringDecoder } from 'node:string_decoder';
    335              * function parseHeader(stream, callback) {
    336              *   stream.on('error', callback);
    337              *   stream.on('readable', onReadable);
    338              *   const decoder = new StringDecoder('utf8');
    339              *   let header = '';
    340              *   function onReadable() {
    341              *     let chunk;
    342              *     while (null !== (chunk = stream.read())) {
    343              *       const str = decoder.write(chunk);
    344              *       if (str.match(/\n\n/)) {
    345              *         // Found the header boundary.
    346              *         const split = str.split(/\n\n/);
    347              *         header += split.shift();
    348              *         const remaining = split.join('\n\n');
    349              *         const buf = Buffer.from(remaining, 'utf8');
    350              *         stream.removeListener('error', callback);
    351              *         // Remove the 'readable' listener before unshifting.
    352              *         stream.removeListener('readable', onReadable);
    353              *         if (buf.length)
    354              *           stream.unshift(buf);
    355              *         // Now the body of the message can be read from the stream.
    356              *         callback(null, header, stream);
    357              *       } else {
    358              *         // Still reading the header.
    359              *         header += str;
    360              *       }
    361              *     }
    362              *   }
    363              * }
    364              * ```
    365              *
    366              * Unlike {@link push}, `stream.unshift(chunk)` will not
    367              * end the reading process by resetting the internal reading state of the stream.
    368              * This can cause unexpected results if `readable.unshift()` is called during a
    369              * read (i.e. from within a {@link _read} implementation on a
    370              * custom stream). Following the call to `readable.unshift()` with an immediate {@link push} will reset the reading state appropriately,
    371              * however it is best to simply avoid calling `readable.unshift()` while in the
    372              * process of performing a read.
    373              * @since v0.9.11
    374              * @param chunk Chunk of data to unshift onto the read queue. For streams not operating in object mode, `chunk` must be a string, `Buffer`, `Uint8Array` or `null`. For object mode
    375              * streams, `chunk` may be any JavaScript value.
    376              * @param encoding Encoding of string chunks. Must be a valid `Buffer` encoding, such as `'utf8'` or `'ascii'`.
    377              */
    378             unshift(chunk: any, encoding?: BufferEncoding): void;
    379             /**
    380              * Prior to Node.js 0.10, streams did not implement the entire `stream` module API
    381              * as it is currently defined. (See `Compatibility` for more information.)
    382              *
    383              * When using an older Node.js library that emits `'data'` events and has a {@link pause} method that is advisory only, the`readable.wrap()` method can be used to create a `Readable`
    384              * stream that uses
    385              * the old stream as its data source.
    386              *
    387              * It will rarely be necessary to use `readable.wrap()` but the method has been
    388              * provided as a convenience for interacting with older Node.js applications and
    389              * libraries.
    390              *
    391              * ```js
    392              * import { OldReader } from './old-api-module.js';
    393              * import { Readable } from 'node:stream';
    394              * const oreader = new OldReader();
    395              * const myReader = new Readable().wrap(oreader);
    396              *
    397              * myReader.on('readable', () => {
    398              *   myReader.read(); // etc.
    399              * });
    400              * ```
    401              * @since v0.9.4
    402              * @param stream An "old style" readable stream
    403              */
    404             wrap(stream: NodeJS.ReadableStream): this;
    405             push(chunk: any, encoding?: BufferEncoding): boolean;
    406             /**
    407              * The iterator created by this method gives users the option to cancel the destruction
    408              * of the stream if the `for await...of` loop is exited by `return`, `break`, or `throw`,
    409              * or if the iterator should destroy the stream if the stream emitted an error during iteration.
    410              * @since v16.3.0
    411              * @param options.destroyOnReturn When set to `false`, calling `return` on the async iterator,
    412              * or exiting a `for await...of` iteration using a `break`, `return`, or `throw` will not destroy the stream.
    413              * **Default: `true`**.
    414              */
    415             iterator(options?: { destroyOnReturn?: boolean }): NodeJS.AsyncIterator<any>;
    416             /**
    417              * This method allows mapping over the stream. The *fn* function will be called for every chunk in the stream.
    418              * If the *fn* function returns a promise - that promise will be `await`ed before being passed to the result stream.
    419              * @since v17.4.0, v16.14.0
    420              * @param fn a function to map over every chunk in the stream. Async or not.
    421              * @returns a stream mapped with the function *fn*.
    422              */
    423             map(fn: (data: any, options?: Pick<ArrayOptions, "signal">) => any, options?: ArrayOptions): Readable;
    424             /**
    425              * This method allows filtering the stream. For each chunk in the stream the *fn* function will be called
    426              * and if it returns a truthy value, the chunk will be passed to the result stream.
    427              * If the *fn* function returns a promise - that promise will be `await`ed.
    428              * @since v17.4.0, v16.14.0
    429              * @param fn a function to filter chunks from the stream. Async or not.
    430              * @returns a stream filtered with the predicate *fn*.
    431              */
    432             filter(
    433                 fn: (data: any, options?: Pick<ArrayOptions, "signal">) => boolean | Promise<boolean>,
    434                 options?: ArrayOptions,
    435             ): Readable;
    436             _destroy(error: Error | null, callback: (error?: Error | null) => void): void;
    437             /**
    438              * Destroy the stream. Optionally emit an `'error'` event, and emit a `'close'`event (unless `emitClose` is set to `false`). After this call, the readable
    439              * stream will release any internal resources and subsequent calls to `push()`will be ignored.
    440              *
    441              * Once `destroy()` has been called any further calls will be a no-op and no
    442              * further errors except from `_destroy()` may be emitted as `'error'`.
    443              *
    444              * Implementors should not override this method, but instead implement `readable._destroy()`.
    445              * @since v8.0.0
    446              * @param error Error which will be passed as payload in `'error'` event
    447              */
    448             destroy(error?: Error): this;
    449             /**
    450              * Event emitter
    451              * The defined events on documents including:
    452              * 1. close
    453              * 2. data
    454              * 3. end
    455              * 4. error
    456              * 5. pause
    457              * 6. readable
    458              * 7. resume
    459              */
    460             addListener(event: "close", listener: () => void): this;
    461             addListener(event: "data", listener: (chunk: any) => void): this;
    462             addListener(event: "end", listener: () => void): this;
    463             addListener(event: "error", listener: (err: Error) => void): this;
    464             addListener(event: "pause", listener: () => void): this;
    465             addListener(event: "readable", listener: () => void): this;
    466             addListener(event: "resume", listener: () => void): this;
    467             addListener(event: string | symbol, listener: (...args: any[]) => void): this;
    468             emit(event: "close"): boolean;
    469             emit(event: "data", chunk: any): boolean;
    470             emit(event: "end"): boolean;
    471             emit(event: "error", err: Error): boolean;
    472             emit(event: "pause"): boolean;
    473             emit(event: "readable"): boolean;
    474             emit(event: "resume"): boolean;
    475             emit(event: string | symbol, ...args: any[]): boolean;
    476             on(event: "close", listener: () => void): this;
    477             on(event: "data", listener: (chunk: any) => void): this;
    478             on(event: "end", listener: () => void): this;
    479             on(event: "error", listener: (err: Error) => void): this;
    480             on(event: "pause", listener: () => void): this;
    481             on(event: "readable", listener: () => void): this;
    482             on(event: "resume", listener: () => void): this;
    483             on(event: string | symbol, listener: (...args: any[]) => void): this;
    484             once(event: "close", listener: () => void): this;
    485             once(event: "data", listener: (chunk: any) => void): this;
    486             once(event: "end", listener: () => void): this;
    487             once(event: "error", listener: (err: Error) => void): this;
    488             once(event: "pause", listener: () => void): this;
    489             once(event: "readable", listener: () => void): this;
    490             once(event: "resume", listener: () => void): this;
    491             once(event: string | symbol, listener: (...args: any[]) => void): this;
    492             prependListener(event: "close", listener: () => void): this;
    493             prependListener(event: "data", listener: (chunk: any) => void): this;
    494             prependListener(event: "end", listener: () => void): this;
    495             prependListener(event: "error", listener: (err: Error) => void): this;
    496             prependListener(event: "pause", listener: () => void): this;
    497             prependListener(event: "readable", listener: () => void): this;
    498             prependListener(event: "resume", listener: () => void): this;
    499             prependListener(event: string | symbol, listener: (...args: any[]) => void): this;
    500             prependOnceListener(event: "close", listener: () => void): this;
    501             prependOnceListener(event: "data", listener: (chunk: any) => void): this;
    502             prependOnceListener(event: "end", listener: () => void): this;
    503             prependOnceListener(event: "error", listener: (err: Error) => void): this;
    504             prependOnceListener(event: "pause", listener: () => void): this;
    505             prependOnceListener(event: "readable", listener: () => void): this;
    506             prependOnceListener(event: "resume", listener: () => void): this;
    507             prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this;
    508             removeListener(event: "close", listener: () => void): this;
    509             removeListener(event: "data", listener: (chunk: any) => void): this;
    510             removeListener(event: "end", listener: () => void): this;
    511             removeListener(event: "error", listener: (err: Error) => void): this;
    512             removeListener(event: "pause", listener: () => void): this;
    513             removeListener(event: "readable", listener: () => void): this;
    514             removeListener(event: "resume", listener: () => void): this;
    515             removeListener(event: string | symbol, listener: (...args: any[]) => void): this;
    516             [Symbol.asyncIterator](): NodeJS.AsyncIterator<any>;
    517         }
    518         interface WritableOptions extends StreamOptions<Writable> {
    519             decodeStrings?: boolean | undefined;
    520             defaultEncoding?: BufferEncoding | undefined;
    521             write?(
    522                 this: Writable,
    523                 chunk: any,
    524                 encoding: BufferEncoding,
    525                 callback: (error?: Error | null) => void,
    526             ): void;
    527             writev?(
    528                 this: Writable,
    529                 chunks: Array<{
    530                     chunk: any;
    531                     encoding: BufferEncoding;
    532                 }>,
    533                 callback: (error?: Error | null) => void,
    534             ): void;
    535             final?(this: Writable, callback: (error?: Error | null) => void): void;
    536         }
    537         /**
    538          * @since v0.9.4
    539          */
    540         class Writable extends Stream implements NodeJS.WritableStream {
    541             /**
    542              * Is `true` if it is safe to call `writable.write()`, which means
    543              * the stream has not been destroyed, errored or ended.
    544              * @since v11.4.0
    545              */
    546             readonly writable: boolean;
    547             /**
    548              * Is `true` after `writable.end()` has been called. This property
    549              * does not indicate whether the data has been flushed, for this use `writable.writableFinished` instead.
    550              * @since v12.9.0
    551              */
    552             readonly writableEnded: boolean;
    553             /**
    554              * Is set to `true` immediately before the `'finish'` event is emitted.
    555              * @since v12.6.0
    556              */
    557             readonly writableFinished: boolean;
    558             /**
    559              * Return the value of `highWaterMark` passed when creating this `Writable`.
    560              * @since v9.3.0
    561              */
    562             readonly writableHighWaterMark: number;
    563             /**
    564              * This property contains the number of bytes (or objects) in the queue
    565              * ready to be written. The value provides introspection data regarding
    566              * the status of the `highWaterMark`.
    567              * @since v9.4.0
    568              */
    569             readonly writableLength: number;
    570             /**
    571              * Getter for the property `objectMode` of a given `Writable` stream.
    572              * @since v12.3.0
    573              */
    574             readonly writableObjectMode: boolean;
    575             /**
    576              * Number of times `writable.uncork()` needs to be
    577              * called in order to fully uncork the stream.
    578              * @since v13.2.0, v12.16.0
    579              */
    580             readonly writableCorked: number;
    581             /**
    582              * Is `true` after `writable.destroy()` has been called.
    583              * @since v8.0.0
    584              */
    585             destroyed: boolean;
    586             constructor(opts?: WritableOptions);
    587             _write(chunk: any, encoding: BufferEncoding, callback: (error?: Error | null) => void): void;
    588             _writev?(
    589                 chunks: Array<{
    590                     chunk: any;
    591                     encoding: BufferEncoding;
    592                 }>,
    593                 callback: (error?: Error | null) => void,
    594             ): void;
    595             _construct?(callback: (error?: Error | null) => void): void;
    596             _destroy(error: Error | null, callback: (error?: Error | null) => void): void;
    597             _final(callback: (error?: Error | null) => void): void;
    598             /**
    599              * The `writable.write()` method writes some data to the stream, and calls the
    600              * supplied `callback` once the data has been fully handled. If an error
    601              * occurs, the `callback` will be called with the error as its
    602              * first argument. The `callback` is called asynchronously and before `'error'` is
    603              * emitted.
    604              *
    605              * The return value is `true` if the internal buffer is less than the`highWaterMark` configured when the stream was created after admitting `chunk`.
    606              * If `false` is returned, further attempts to write data to the stream should
    607              * stop until the `'drain'` event is emitted.
    608              *
    609              * While a stream is not draining, calls to `write()` will buffer `chunk`, and
    610              * return false. Once all currently buffered chunks are drained (accepted for
    611              * delivery by the operating system), the `'drain'` event will be emitted.
    612              * It is recommended that once `write()` returns false, no more chunks be written
    613              * until the `'drain'` event is emitted. While calling `write()` on a stream that
    614              * is not draining is allowed, Node.js will buffer all written chunks until
    615              * maximum memory usage occurs, at which point it will abort unconditionally.
    616              * Even before it aborts, high memory usage will cause poor garbage collector
    617              * performance and high RSS (which is not typically released back to the system,
    618              * even after the memory is no longer required). Since TCP sockets may never
    619              * drain if the remote peer does not read the data, writing a socket that is
    620              * not draining may lead to a remotely exploitable vulnerability.
    621              *
    622              * Writing data while the stream is not draining is particularly
    623              * problematic for a `Transform`, because the `Transform` streams are paused
    624              * by default until they are piped or a `'data'` or `'readable'` event handler
    625              * is added.
    626              *
    627              * If the data to be written can be generated or fetched on demand, it is
    628              * recommended to encapsulate the logic into a `Readable` and use {@link pipe}. However, if calling `write()` is preferred, it is
    629              * possible to respect backpressure and avoid memory issues using the `'drain'` event:
    630              *
    631              * ```js
    632              * function write(data, cb) {
    633              *   if (!stream.write(data)) {
    634              *     stream.once('drain', cb);
    635              *   } else {
    636              *     process.nextTick(cb);
    637              *   }
    638              * }
    639              *
    640              * // Wait for cb to be called before doing any other write.
    641              * write('hello', () => {
    642              *   console.log('Write completed, do more writes now.');
    643              * });
    644              * ```
    645              *
    646              * A `Writable` stream in object mode will always ignore the `encoding` argument.
    647              * @since v0.9.4
    648              * @param chunk Optional data to write. For streams not operating in object mode, `chunk` must be a string, `Buffer` or `Uint8Array`. For object mode streams, `chunk` may be any
    649              * JavaScript value other than `null`.
    650              * @param [encoding='utf8'] The encoding, if `chunk` is a string.
    651              * @param callback Callback for when this chunk of data is flushed.
    652              * @return `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`.
    653              */
    654             write(chunk: any, callback?: (error: Error | null | undefined) => void): boolean;
    655             write(chunk: any, encoding: BufferEncoding, callback?: (error: Error | null | undefined) => void): boolean;
    656             /**
    657              * The `writable.setDefaultEncoding()` method sets the default `encoding` for a `Writable` stream.
    658              * @since v0.11.15
    659              * @param encoding The new default encoding
    660              */
    661             setDefaultEncoding(encoding: BufferEncoding): this;
    662             /**
    663              * Calling the `writable.end()` method signals that no more data will be written
    664              * to the `Writable`. The optional `chunk` and `encoding` arguments allow one
    665              * final additional chunk of data to be written immediately before closing the
    666              * stream.
    667              *
    668              * Calling the {@link write} method after calling {@link end} will raise an error.
    669              *
    670              * ```js
    671              * // Write 'hello, ' and then end with 'world!'.
    672              * import fs from 'node:fs';
    673              * const file = fs.createWriteStream('example.txt');
    674              * file.write('hello, ');
    675              * file.end('world!');
    676              * // Writing more now is not allowed!
    677              * ```
    678              * @since v0.9.4
    679              * @param chunk Optional data to write. For streams not operating in object mode, `chunk` must be a string, `Buffer` or `Uint8Array`. For object mode streams, `chunk` may be any
    680              * JavaScript value other than `null`.
    681              * @param encoding The encoding if `chunk` is a string
    682              * @param callback Callback for when the stream is finished.
    683              */
    684             end(cb?: () => void): this;
    685             end(chunk: any, cb?: () => void): this;
    686             end(chunk: any, encoding: BufferEncoding, cb?: () => void): this;
    687             /**
    688              * The `writable.cork()` method forces all written data to be buffered in memory.
    689              * The buffered data will be flushed when either the {@link uncork} or {@link end} methods are called.
    690              *
    691              * The primary intent of `writable.cork()` is to accommodate a situation in which
    692              * several small chunks are written to the stream in rapid succession. Instead of
    693              * immediately forwarding them to the underlying destination, `writable.cork()`buffers all the chunks until `writable.uncork()` is called, which will pass them
    694              * all to `writable._writev()`, if present. This prevents a head-of-line blocking
    695              * situation where data is being buffered while waiting for the first small chunk
    696              * to be processed. However, use of `writable.cork()` without implementing`writable._writev()` may have an adverse effect on throughput.
    697              *
    698              * See also: `writable.uncork()`, `writable._writev()`.
    699              * @since v0.11.2
    700              */
    701             cork(): void;
    702             /**
    703              * The `writable.uncork()` method flushes all data buffered since {@link cork} was called.
    704              *
    705              * When using `writable.cork()` and `writable.uncork()` to manage the buffering
    706              * of writes to a stream, it is recommended that calls to `writable.uncork()` be
    707              * deferred using `process.nextTick()`. Doing so allows batching of all`writable.write()` calls that occur within a given Node.js event loop phase.
    708              *
    709              * ```js
    710              * stream.cork();
    711              * stream.write('some ');
    712              * stream.write('data ');
    713              * process.nextTick(() => stream.uncork());
    714              * ```
    715              *
    716              * If the `writable.cork()` method is called multiple times on a stream, the
    717              * same number of calls to `writable.uncork()` must be called to flush the buffered
    718              * data.
    719              *
    720              * ```js
    721              * stream.cork();
    722              * stream.write('some ');
    723              * stream.cork();
    724              * stream.write('data ');
    725              * process.nextTick(() => {
    726              *   stream.uncork();
    727              *   // The data will not be flushed until uncork() is called a second time.
    728              *   stream.uncork();
    729              * });
    730              * ```
    731              *
    732              * See also: `writable.cork()`.
    733              * @since v0.11.2
    734              */
    735             uncork(): void;
    736             /**
    737              * Destroy the stream. Optionally emit an `'error'` event, and emit a `'close'`event (unless `emitClose` is set to `false`). After this call, the writable
    738              * stream has ended and subsequent calls to `write()` or `end()` will result in
    739              * an `ERR_STREAM_DESTROYED` error.
    740              * This is a destructive and immediate way to destroy a stream. Previous calls to`write()` may not have drained, and may trigger an `ERR_STREAM_DESTROYED` error.
    741              * Use `end()` instead of destroy if data should flush before close, or wait for
    742              * the `'drain'` event before destroying the stream.
    743              *
    744              * Once `destroy()` has been called any further calls will be a no-op and no
    745              * further errors except from `_destroy()` may be emitted as `'error'`.
    746              *
    747              * Implementors should not override this method,
    748              * but instead implement `writable._destroy()`.
    749              * @since v8.0.0
    750              * @param error Optional, an error to emit with `'error'` event.
    751              */
    752             destroy(error?: Error): this;
    753             /**
    754              * Event emitter
    755              * The defined events on documents including:
    756              * 1. close
    757              * 2. drain
    758              * 3. error
    759              * 4. finish
    760              * 5. pipe
    761              * 6. unpipe
    762              */
    763             addListener(event: "close", listener: () => void): this;
    764             addListener(event: "drain", listener: () => void): this;
    765             addListener(event: "error", listener: (err: Error) => void): this;
    766             addListener(event: "finish", listener: () => void): this;
    767             addListener(event: "pipe", listener: (src: Readable) => void): this;
    768             addListener(event: "unpipe", listener: (src: Readable) => void): this;
    769             addListener(event: string | symbol, listener: (...args: any[]) => void): this;
    770             emit(event: "close"): boolean;
    771             emit(event: "drain"): boolean;
    772             emit(event: "error", err: Error): boolean;
    773             emit(event: "finish"): boolean;
    774             emit(event: "pipe", src: Readable): boolean;
    775             emit(event: "unpipe", src: Readable): boolean;
    776             emit(event: string | symbol, ...args: any[]): boolean;
    777             on(event: "close", listener: () => void): this;
    778             on(event: "drain", listener: () => void): this;
    779             on(event: "error", listener: (err: Error) => void): this;
    780             on(event: "finish", listener: () => void): this;
    781             on(event: "pipe", listener: (src: Readable) => void): this;
    782             on(event: "unpipe", listener: (src: Readable) => void): this;
    783             on(event: string | symbol, listener: (...args: any[]) => void): this;
    784             once(event: "close", listener: () => void): this;
    785             once(event: "drain", listener: () => void): this;
    786             once(event: "error", listener: (err: Error) => void): this;
    787             once(event: "finish", listener: () => void): this;
    788             once(event: "pipe", listener: (src: Readable) => void): this;
    789             once(event: "unpipe", listener: (src: Readable) => void): this;
    790             once(event: string | symbol, listener: (...args: any[]) => void): this;
    791             prependListener(event: "close", listener: () => void): this;
    792             prependListener(event: "drain", listener: () => void): this;
    793             prependListener(event: "error", listener: (err: Error) => void): this;
    794             prependListener(event: "finish", listener: () => void): this;
    795             prependListener(event: "pipe", listener: (src: Readable) => void): this;
    796             prependListener(event: "unpipe", listener: (src: Readable) => void): this;
    797             prependListener(event: string | symbol, listener: (...args: any[]) => void): this;
    798             prependOnceListener(event: "close", listener: () => void): this;
    799             prependOnceListener(event: "drain", listener: () => void): this;
    800             prependOnceListener(event: "error", listener: (err: Error) => void): this;
    801             prependOnceListener(event: "finish", listener: () => void): this;
    802             prependOnceListener(event: "pipe", listener: (src: Readable) => void): this;
    803             prependOnceListener(event: "unpipe", listener: (src: Readable) => void): this;
    804             prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this;
    805             removeListener(event: "close", listener: () => void): this;
    806             removeListener(event: "drain", listener: () => void): this;
    807             removeListener(event: "error", listener: (err: Error) => void): this;
    808             removeListener(event: "finish", listener: () => void): this;
    809             removeListener(event: "pipe", listener: (src: Readable) => void): this;
    810             removeListener(event: "unpipe", listener: (src: Readable) => void): this;
    811             removeListener(event: string | symbol, listener: (...args: any[]) => void): this;
    812         }
    813         interface DuplexOptions extends ReadableOptions, WritableOptions {
    814             allowHalfOpen?: boolean | undefined;
    815             readableObjectMode?: boolean | undefined;
    816             writableObjectMode?: boolean | undefined;
    817             readableHighWaterMark?: number | undefined;
    818             writableHighWaterMark?: number | undefined;
    819             writableCorked?: number | undefined;
    820             construct?(this: Duplex, callback: (error?: Error | null) => void): void;
    821             read?(this: Duplex, size: number): void;
    822             write?(this: Duplex, chunk: any, encoding: BufferEncoding, callback: (error?: Error | null) => void): void;
    823             writev?(
    824                 this: Duplex,
    825                 chunks: Array<{
    826                     chunk: any;
    827                     encoding: BufferEncoding;
    828                 }>,
    829                 callback: (error?: Error | null) => void,
    830             ): void;
    831             final?(this: Duplex, callback: (error?: Error | null) => void): void;
    832             destroy?(this: Duplex, error: Error | null, callback: (error?: Error | null) => void): void;
    833         }
    834         /**
    835          * Duplex streams are streams that implement both the `Readable` and `Writable` interfaces.
    836          *
    837          * Examples of `Duplex` streams include:
    838          *
    839          * * `TCP sockets`
    840          * * `zlib streams`
    841          * * `crypto streams`
    842          * @since v0.9.4
    843          */
    844         class Duplex extends Readable implements Writable {
    845             readonly writable: boolean;
    846             readonly writableEnded: boolean;
    847             readonly writableFinished: boolean;
    848             readonly writableHighWaterMark: number;
    849             readonly writableLength: number;
    850             readonly writableObjectMode: boolean;
    851             readonly writableCorked: number;
    852             /**
    853              * If `false` then the stream will automatically end the writable side when the
    854              * readable side ends. Set initially by the `allowHalfOpen` constructor option,
    855              * which defaults to `false`.
    856              *
    857              * This can be changed manually to change the half-open behavior of an existing`Duplex` stream instance, but must be changed before the `'end'` event is
    858              * emitted.
    859              * @since v0.9.4
    860              */
    861             allowHalfOpen: boolean;
    862             constructor(opts?: DuplexOptions);
    863             /**
    864              * A utility method for creating duplex streams.
    865              *
    866              * - `Stream` converts writable stream into writable `Duplex` and readable stream
    867              *   to `Duplex`.
    868              * - `Blob` converts into readable `Duplex`.
    869              * - `string` converts into readable `Duplex`.
    870              * - `ArrayBuffer` converts into readable `Duplex`.
    871              * - `AsyncIterable` converts into a readable `Duplex`. Cannot yield `null`.
    872              * - `AsyncGeneratorFunction` converts into a readable/writable transform
    873              *   `Duplex`. Must take a source `AsyncIterable` as first parameter. Cannot yield
    874              *   `null`.
    875              * - `AsyncFunction` converts into a writable `Duplex`. Must return
    876              *   either `null` or `undefined`
    877              * - `Object ({ writable, readable })` converts `readable` and
    878              *   `writable` into `Stream` and then combines them into `Duplex` where the
    879              *   `Duplex` will write to the `writable` and read from the `readable`.
    880              * - `Promise` converts into readable `Duplex`. Value `null` is ignored.
    881              *
    882              * @since v16.8.0
    883              */
    884             static from(
    885                 src:
    886                     | Stream
    887                     | NodeBlob
    888                     | ArrayBuffer
    889                     | string
    890                     | Iterable<any>
    891                     | AsyncIterable<any>
    892                     | AsyncGeneratorFunction
    893                     | Promise<any>
    894                     | Object,
    895             ): Duplex;
    896             _write(chunk: any, encoding: BufferEncoding, callback: (error?: Error | null) => void): void;
    897             _writev?(
    898                 chunks: Array<{
    899                     chunk: any;
    900                     encoding: BufferEncoding;
    901                 }>,
    902                 callback: (error?: Error | null) => void,
    903             ): void;
    904             _destroy(error: Error | null, callback: (error?: Error | null) => void): void;
    905             _final(callback: (error?: Error | null) => void): void;
    906             write(chunk: any, encoding?: BufferEncoding, cb?: (error: Error | null | undefined) => void): boolean;
    907             write(chunk: any, cb?: (error: Error | null | undefined) => void): boolean;
    908             setDefaultEncoding(encoding: BufferEncoding): this;
    909             end(cb?: () => void): this;
    910             end(chunk: any, cb?: () => void): this;
    911             end(chunk: any, encoding?: BufferEncoding, cb?: () => void): this;
    912             cork(): void;
    913             uncork(): void;
    914             /**
    915              * Event emitter
    916              * The defined events on documents including:
    917              * 1.  close
    918              * 2.  data
    919              * 3.  drain
    920              * 4.  end
    921              * 5.  error
    922              * 6.  finish
    923              * 7.  pause
    924              * 8.  pipe
    925              * 9.  readable
    926              * 10. resume
    927              * 11. unpipe
    928              */
    929             addListener(event: "close", listener: () => void): this;
    930             addListener(event: "data", listener: (chunk: any) => void): this;
    931             addListener(event: "drain", listener: () => void): this;
    932             addListener(event: "end", listener: () => void): this;
    933             addListener(event: "error", listener: (err: Error) => void): this;
    934             addListener(event: "finish", listener: () => void): this;
    935             addListener(event: "pause", listener: () => void): this;
    936             addListener(event: "pipe", listener: (src: Readable) => void): this;
    937             addListener(event: "readable", listener: () => void): this;
    938             addListener(event: "resume", listener: () => void): this;
    939             addListener(event: "unpipe", listener: (src: Readable) => void): this;
    940             addListener(event: string | symbol, listener: (...args: any[]) => void): this;
    941             emit(event: "close"): boolean;
    942             emit(event: "data", chunk: any): boolean;
    943             emit(event: "drain"): boolean;
    944             emit(event: "end"): boolean;
    945             emit(event: "error", err: Error): boolean;
    946             emit(event: "finish"): boolean;
    947             emit(event: "pause"): boolean;
    948             emit(event: "pipe", src: Readable): boolean;
    949             emit(event: "readable"): boolean;
    950             emit(event: "resume"): boolean;
    951             emit(event: "unpipe", src: Readable): boolean;
    952             emit(event: string | symbol, ...args: any[]): boolean;
    953             on(event: "close", listener: () => void): this;
    954             on(event: "data", listener: (chunk: any) => void): this;
    955             on(event: "drain", listener: () => void): this;
    956             on(event: "end", listener: () => void): this;
    957             on(event: "error", listener: (err: Error) => void): this;
    958             on(event: "finish", listener: () => void): this;
    959             on(event: "pause", listener: () => void): this;
    960             on(event: "pipe", listener: (src: Readable) => void): this;
    961             on(event: "readable", listener: () => void): this;
    962             on(event: "resume", listener: () => void): this;
    963             on(event: "unpipe", listener: (src: Readable) => void): this;
    964             on(event: string | symbol, listener: (...args: any[]) => void): this;
    965             once(event: "close", listener: () => void): this;
    966             once(event: "data", listener: (chunk: any) => void): this;
    967             once(event: "drain", listener: () => void): this;
    968             once(event: "end", listener: () => void): this;
    969             once(event: "error", listener: (err: Error) => void): this;
    970             once(event: "finish", listener: () => void): this;
    971             once(event: "pause", listener: () => void): this;
    972             once(event: "pipe", listener: (src: Readable) => void): this;
    973             once(event: "readable", listener: () => void): this;
    974             once(event: "resume", listener: () => void): this;
    975             once(event: "unpipe", listener: (src: Readable) => void): this;
    976             once(event: string | symbol, listener: (...args: any[]) => void): this;
    977             prependListener(event: "close", listener: () => void): this;
    978             prependListener(event: "data", listener: (chunk: any) => void): this;
    979             prependListener(event: "drain", listener: () => void): this;
    980             prependListener(event: "end", listener: () => void): this;
    981             prependListener(event: "error", listener: (err: Error) => void): this;
    982             prependListener(event: "finish", listener: () => void): this;
    983             prependListener(event: "pause", listener: () => void): this;
    984             prependListener(event: "pipe", listener: (src: Readable) => void): this;
    985             prependListener(event: "readable", listener: () => void): this;
    986             prependListener(event: "resume", listener: () => void): this;
    987             prependListener(event: "unpipe", listener: (src: Readable) => void): this;
    988             prependListener(event: string | symbol, listener: (...args: any[]) => void): this;
    989             prependOnceListener(event: "close", listener: () => void): this;
    990             prependOnceListener(event: "data", listener: (chunk: any) => void): this;
    991             prependOnceListener(event: "drain", listener: () => void): this;
    992             prependOnceListener(event: "end", listener: () => void): this;
    993             prependOnceListener(event: "error", listener: (err: Error) => void): this;
    994             prependOnceListener(event: "finish", listener: () => void): this;
    995             prependOnceListener(event: "pause", listener: () => void): this;
    996             prependOnceListener(event: "pipe", listener: (src: Readable) => void): this;
    997             prependOnceListener(event: "readable", listener: () => void): this;
    998             prependOnceListener(event: "resume", listener: () => void): this;
    999             prependOnceListener(event: "unpipe", listener: (src: Readable) => void): this;
   1000             prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this;
   1001             removeListener(event: "close", listener: () => void): this;
   1002             removeListener(event: "data", listener: (chunk: any) => void): this;
   1003             removeListener(event: "drain", listener: () => void): this;
   1004             removeListener(event: "end", listener: () => void): this;
   1005             removeListener(event: "error", listener: (err: Error) => void): this;
   1006             removeListener(event: "finish", listener: () => void): this;
   1007             removeListener(event: "pause", listener: () => void): this;
   1008             removeListener(event: "pipe", listener: (src: Readable) => void): this;
   1009             removeListener(event: "readable", listener: () => void): this;
   1010             removeListener(event: "resume", listener: () => void): this;
   1011             removeListener(event: "unpipe", listener: (src: Readable) => void): this;
   1012             removeListener(event: string | symbol, listener: (...args: any[]) => void): this;
   1013         }
   1014         type TransformCallback = (error?: Error | null, data?: any) => void;
   1015         interface TransformOptions extends DuplexOptions {
   1016             construct?(this: Transform, callback: (error?: Error | null) => void): void;
   1017             read?(this: Transform, size: number): void;
   1018             write?(
   1019                 this: Transform,
   1020                 chunk: any,
   1021                 encoding: BufferEncoding,
   1022                 callback: (error?: Error | null) => void,
   1023             ): void;
   1024             writev?(
   1025                 this: Transform,
   1026                 chunks: Array<{
   1027                     chunk: any;
   1028                     encoding: BufferEncoding;
   1029                 }>,
   1030                 callback: (error?: Error | null) => void,
   1031             ): void;
   1032             final?(this: Transform, callback: (error?: Error | null) => void): void;
   1033             destroy?(this: Transform, error: Error | null, callback: (error?: Error | null) => void): void;
   1034             transform?(this: Transform, chunk: any, encoding: BufferEncoding, callback: TransformCallback): void;
   1035             flush?(this: Transform, callback: TransformCallback): void;
   1036         }
   1037         /**
   1038          * Transform streams are `Duplex` streams where the output is in some way
   1039          * related to the input. Like all `Duplex` streams, `Transform` streams
   1040          * implement both the `Readable` and `Writable` interfaces.
   1041          *
   1042          * Examples of `Transform` streams include:
   1043          *
   1044          * * `zlib streams`
   1045          * * `crypto streams`
   1046          * @since v0.9.4
   1047          */
   1048         class Transform extends Duplex {
   1049             constructor(opts?: TransformOptions);
   1050             _transform(chunk: any, encoding: BufferEncoding, callback: TransformCallback): void;
   1051             _flush(callback: TransformCallback): void;
   1052         }
   1053         /**
   1054          * The `stream.PassThrough` class is a trivial implementation of a `Transform` stream that simply passes the input bytes across to the output. Its purpose is
   1055          * primarily for examples and testing, but there are some use cases where`stream.PassThrough` is useful as a building block for novel sorts of streams.
   1056          */
   1057         class PassThrough extends Transform {}
   1058         /**
   1059          * Attaches an AbortSignal to a readable or writeable stream. This lets code
   1060          * control stream destruction using an `AbortController`.
   1061          *
   1062          * Calling `abort` on the `AbortController` corresponding to the passed`AbortSignal` will behave the same way as calling `.destroy(new AbortError())`on the stream.
   1063          *
   1064          * ```js
   1065          * import fs from 'node:fs';
   1066          *
   1067          * const controller = new AbortController();
   1068          * const read = addAbortSignal(
   1069          *   controller.signal,
   1070          *   fs.createReadStream(('object.json'))
   1071          * );
   1072          * // Later, abort the operation closing the stream
   1073          * controller.abort();
   1074          * ```
   1075          *
   1076          * Or using an `AbortSignal` with a readable stream as an async iterable:
   1077          *
   1078          * ```js
   1079          * const controller = new AbortController();
   1080          * setTimeout(() => controller.abort(), 10_000); // set a timeout
   1081          * const stream = addAbortSignal(
   1082          *   controller.signal,
   1083          *   fs.createReadStream(('object.json'))
   1084          * );
   1085          * (async () => {
   1086          *   try {
   1087          *     for await (const chunk of stream) {
   1088          *       await process(chunk);
   1089          *     }
   1090          *   } catch (e) {
   1091          *     if (e.name === 'AbortError') {
   1092          *       // The operation was cancelled
   1093          *     } else {
   1094          *       throw e;
   1095          *     }
   1096          *   }
   1097          * })();
   1098          * ```
   1099          * @since v15.4.0
   1100          * @param signal A signal representing possible cancellation
   1101          * @param stream a stream to attach a signal to
   1102          */
   1103         function addAbortSignal<T extends Stream>(signal: AbortSignal, stream: T): T;
   1104         interface FinishedOptions extends Abortable {
   1105             error?: boolean | undefined;
   1106             readable?: boolean | undefined;
   1107             writable?: boolean | undefined;
   1108         }
   1109         /**
   1110          * A function to get notified when a stream is no longer readable, writable
   1111          * or has experienced an error or a premature close event.
   1112          *
   1113          * ```js
   1114          * import { finished } from 'node:stream';
   1115          *
   1116          * const rs = fs.createReadStream('archive.tar');
   1117          *
   1118          * finished(rs, (err) => {
   1119          *   if (err) {
   1120          *     console.error('Stream failed.', err);
   1121          *   } else {
   1122          *     console.log('Stream is done reading.');
   1123          *   }
   1124          * });
   1125          *
   1126          * rs.resume(); // Drain the stream.
   1127          * ```
   1128          *
   1129          * Especially useful in error handling scenarios where a stream is destroyed
   1130          * prematurely (like an aborted HTTP request), and will not emit `'end'` or `'finish'`.
   1131          *
   1132          * The `finished` API provides promise version:
   1133          *
   1134          * ```js
   1135          * import { finished } from 'node:stream/promises';
   1136          *
   1137          * const rs = fs.createReadStream('archive.tar');
   1138          *
   1139          * async function run() {
   1140          *   await finished(rs);
   1141          *   console.log('Stream is done reading.');
   1142          * }
   1143          *
   1144          * run().catch(console.error);
   1145          * rs.resume(); // Drain the stream.
   1146          * ```
   1147          *
   1148          * `stream.finished()` leaves dangling event listeners (in particular`'error'`, `'end'`, `'finish'` and `'close'`) after `callback` has been
   1149          * invoked. The reason for this is so that unexpected `'error'` events (due to
   1150          * incorrect stream implementations) do not cause unexpected crashes.
   1151          * If this is unwanted behavior then the returned cleanup function needs to be
   1152          * invoked in the callback:
   1153          *
   1154          * ```js
   1155          * const cleanup = finished(rs, (err) => {
   1156          *   cleanup();
   1157          *   // ...
   1158          * });
   1159          * ```
   1160          * @since v10.0.0
   1161          * @param stream A readable and/or writable stream.
   1162          * @param callback A callback function that takes an optional error argument.
   1163          * @return A cleanup function which removes all registered listeners.
   1164          */
   1165         function finished(
   1166             stream: NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream,
   1167             options: FinishedOptions,
   1168             callback: (err?: NodeJS.ErrnoException | null) => void,
   1169         ): () => void;
   1170         function finished(
   1171             stream: NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream,
   1172             callback: (err?: NodeJS.ErrnoException | null) => void,
   1173         ): () => void;
   1174         namespace finished {
   1175             function __promisify__(
   1176                 stream: NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream,
   1177                 options?: FinishedOptions,
   1178             ): Promise<void>;
   1179         }
   1180         type PipelineSourceFunction<T> = () => Iterable<T> | AsyncIterable<T>;
   1181         type PipelineSource<T> = Iterable<T> | AsyncIterable<T> | NodeJS.ReadableStream | PipelineSourceFunction<T>;
   1182         type PipelineTransform<S extends PipelineTransformSource<any>, U> =
   1183             | NodeJS.ReadWriteStream
   1184             | ((
   1185                 source: S extends (...args: any[]) => Iterable<infer ST> | AsyncIterable<infer ST> ? AsyncIterable<ST>
   1186                     : S,
   1187             ) => AsyncIterable<U>);
   1188         type PipelineTransformSource<T> = PipelineSource<T> | PipelineTransform<any, T>;
   1189         type PipelineDestinationIterableFunction<T> = (source: AsyncIterable<T>) => AsyncIterable<any>;
   1190         type PipelineDestinationPromiseFunction<T, P> = (source: AsyncIterable<T>) => Promise<P>;
   1191         type PipelineDestination<S extends PipelineTransformSource<any>, P> = S extends
   1192             PipelineTransformSource<infer ST> ?
   1193                 | NodeJS.WritableStream
   1194                 | PipelineDestinationIterableFunction<ST>
   1195                 | PipelineDestinationPromiseFunction<ST, P>
   1196             : never;
   1197         type PipelineCallback<S extends PipelineDestination<any, any>> = S extends
   1198             PipelineDestinationPromiseFunction<any, infer P> ? (err: NodeJS.ErrnoException | null, value: P) => void
   1199             : (err: NodeJS.ErrnoException | null) => void;
   1200         type PipelinePromise<S extends PipelineDestination<any, any>> = S extends
   1201             PipelineDestinationPromiseFunction<any, infer P> ? Promise<P> : Promise<void>;
   1202         interface PipelineOptions {
   1203             signal?: AbortSignal | undefined;
   1204             end?: boolean | undefined;
   1205         }
   1206         /**
   1207          * A module method to pipe between streams and generators forwarding errors and
   1208          * properly cleaning up and provide a callback when the pipeline is complete.
   1209          *
   1210          * ```js
   1211          * import { pipeline } from 'node:stream';
   1212          * import fs from 'node:fs';
   1213          * import zlib from 'node:zlib';
   1214          *
   1215          * // Use the pipeline API to easily pipe a series of streams
   1216          * // together and get notified when the pipeline is fully done.
   1217          *
   1218          * // A pipeline to gzip a potentially huge tar file efficiently:
   1219          *
   1220          * pipeline(
   1221          *   fs.createReadStream('archive.tar'),
   1222          *   zlib.createGzip(),
   1223          *   fs.createWriteStream('archive.tar.gz'),
   1224          *   (err) => {
   1225          *     if (err) {
   1226          *       console.error('Pipeline failed.', err);
   1227          *     } else {
   1228          *       console.log('Pipeline succeeded.');
   1229          *     }
   1230          *   }
   1231          * );
   1232          * ```
   1233          *
   1234          * The `pipeline` API provides a promise version, which can also
   1235          * receive an options argument as the last parameter with a`signal` `AbortSignal` property. When the signal is aborted,`destroy` will be called on the underlying pipeline, with
   1236          * an`AbortError`.
   1237          *
   1238          * ```js
   1239          * import { pipeline } from 'node:stream/promises';
   1240          *
   1241          * async function run() {
   1242          *   await pipeline(
   1243          *     fs.createReadStream('archive.tar'),
   1244          *     zlib.createGzip(),
   1245          *     fs.createWriteStream('archive.tar.gz')
   1246          *   );
   1247          *   console.log('Pipeline succeeded.');
   1248          * }
   1249          *
   1250          * run().catch(console.error);
   1251          * ```
   1252          *
   1253          * To use an `AbortSignal`, pass it inside an options object,
   1254          * as the last argument:
   1255          *
   1256          * ```js
   1257          * import { pipeline } from 'node:stream/promises';
   1258          *
   1259          * async function run() {
   1260          *   const ac = new AbortController();
   1261          *   const signal = ac.signal;
   1262          *
   1263          *   setTimeout(() => ac.abort(), 1);
   1264          *   await pipeline(
   1265          *     fs.createReadStream('archive.tar'),
   1266          *     zlib.createGzip(),
   1267          *     fs.createWriteStream('archive.tar.gz'),
   1268          *     { signal },
   1269          *   );
   1270          * }
   1271          *
   1272          * run().catch(console.error); // AbortError
   1273          * ```
   1274          *
   1275          * The `pipeline` API also supports async generators:
   1276          *
   1277          * ```js
   1278          * import { pipeline } from 'node:stream/promises';
   1279          * import fs from 'node:fs';
   1280          *
   1281          * async function run() {
   1282          *   await pipeline(
   1283          *     fs.createReadStream('lowercase.txt'),
   1284          *     async function* (source, signal) {
   1285          *       source.setEncoding('utf8');  // Work with strings rather than `Buffer`s.
   1286          *       for await (const chunk of source) {
   1287          *         yield await processChunk(chunk, { signal });
   1288          *       }
   1289          *     },
   1290          *     fs.createWriteStream('uppercase.txt')
   1291          *   );
   1292          *   console.log('Pipeline succeeded.');
   1293          * }
   1294          *
   1295          * run().catch(console.error);
   1296          * ```
   1297          *
   1298          * Remember to handle the `signal` argument passed into the async generator.
   1299          * Especially in the case where the async generator is the source for the
   1300          * pipeline (i.e. first argument) or the pipeline will never complete.
   1301          *
   1302          * ```js
   1303          * import { pipeline } from 'node:stream/promises';
   1304          * import fs from 'node:fs';
   1305          *
   1306          * async function run() {
   1307          *   await pipeline(
   1308          *     async function * (signal) {
   1309          *       await someLongRunningfn({ signal });
   1310          *       yield 'asd';
   1311          *     },
   1312          *     fs.createWriteStream('uppercase.txt')
   1313          *   );
   1314          *   console.log('Pipeline succeeded.');
   1315          * }
   1316          *
   1317          * run().catch(console.error);
   1318          * ```
   1319          *
   1320          * `stream.pipeline()` will call `stream.destroy(err)` on all streams except:
   1321          *
   1322          * * `Readable` streams which have emitted `'end'` or `'close'`.
   1323          * * `Writable` streams which have emitted `'finish'` or `'close'`.
   1324          *
   1325          * `stream.pipeline()` leaves dangling event listeners on the streams
   1326          * after the `callback` has been invoked. In the case of reuse of streams after
   1327          * failure, this can cause event listener leaks and swallowed errors.
   1328          * @since v10.0.0
   1329          * @param callback Called when the pipeline is fully done.
   1330          */
   1331         function pipeline<A extends PipelineSource<any>, B extends PipelineDestination<A, any>>(
   1332             source: A,
   1333             destination: B,
   1334             callback?: PipelineCallback<B>,
   1335         ): B extends NodeJS.WritableStream ? B : NodeJS.WritableStream;
   1336         function pipeline<
   1337             A extends PipelineSource<any>,
   1338             T1 extends PipelineTransform<A, any>,
   1339             B extends PipelineDestination<T1, any>,
   1340         >(
   1341             source: A,
   1342             transform1: T1,
   1343             destination: B,
   1344             callback?: PipelineCallback<B>,
   1345         ): B extends NodeJS.WritableStream ? B : NodeJS.WritableStream;
   1346         function pipeline<
   1347             A extends PipelineSource<any>,
   1348             T1 extends PipelineTransform<A, any>,
   1349             T2 extends PipelineTransform<T1, any>,
   1350             B extends PipelineDestination<T2, any>,
   1351         >(
   1352             source: A,
   1353             transform1: T1,
   1354             transform2: T2,
   1355             destination: B,
   1356             callback?: PipelineCallback<B>,
   1357         ): B extends NodeJS.WritableStream ? B : NodeJS.WritableStream;
   1358         function pipeline<
   1359             A extends PipelineSource<any>,
   1360             T1 extends PipelineTransform<A, any>,
   1361             T2 extends PipelineTransform<T1, any>,
   1362             T3 extends PipelineTransform<T2, any>,
   1363             B extends PipelineDestination<T3, any>,
   1364         >(
   1365             source: A,
   1366             transform1: T1,
   1367             transform2: T2,
   1368             transform3: T3,
   1369             destination: B,
   1370             callback?: PipelineCallback<B>,
   1371         ): B extends NodeJS.WritableStream ? B : NodeJS.WritableStream;
   1372         function pipeline<
   1373             A extends PipelineSource<any>,
   1374             T1 extends PipelineTransform<A, any>,
   1375             T2 extends PipelineTransform<T1, any>,
   1376             T3 extends PipelineTransform<T2, any>,
   1377             T4 extends PipelineTransform<T3, any>,
   1378             B extends PipelineDestination<T4, any>,
   1379         >(
   1380             source: A,
   1381             transform1: T1,
   1382             transform2: T2,
   1383             transform3: T3,
   1384             transform4: T4,
   1385             destination: B,
   1386             callback?: PipelineCallback<B>,
   1387         ): B extends NodeJS.WritableStream ? B : NodeJS.WritableStream;
   1388         function pipeline(
   1389             streams: ReadonlyArray<NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream>,
   1390             callback?: (err: NodeJS.ErrnoException | null) => void,
   1391         ): NodeJS.WritableStream;
   1392         function pipeline(
   1393             stream1: NodeJS.ReadableStream,
   1394             stream2: NodeJS.ReadWriteStream | NodeJS.WritableStream,
   1395             ...streams: Array<
   1396                 NodeJS.ReadWriteStream | NodeJS.WritableStream | ((err: NodeJS.ErrnoException | null) => void)
   1397             >
   1398         ): NodeJS.WritableStream;
   1399         namespace pipeline {
   1400             function __promisify__<A extends PipelineSource<any>, B extends PipelineDestination<A, any>>(
   1401                 source: A,
   1402                 destination: B,
   1403                 options?: PipelineOptions,
   1404             ): PipelinePromise<B>;
   1405             function __promisify__<
   1406                 A extends PipelineSource<any>,
   1407                 T1 extends PipelineTransform<A, any>,
   1408                 B extends PipelineDestination<T1, any>,
   1409             >(
   1410                 source: A,
   1411                 transform1: T1,
   1412                 destination: B,
   1413                 options?: PipelineOptions,
   1414             ): PipelinePromise<B>;
   1415             function __promisify__<
   1416                 A extends PipelineSource<any>,
   1417                 T1 extends PipelineTransform<A, any>,
   1418                 T2 extends PipelineTransform<T1, any>,
   1419                 B extends PipelineDestination<T2, any>,
   1420             >(
   1421                 source: A,
   1422                 transform1: T1,
   1423                 transform2: T2,
   1424                 destination: B,
   1425                 options?: PipelineOptions,
   1426             ): PipelinePromise<B>;
   1427             function __promisify__<
   1428                 A extends PipelineSource<any>,
   1429                 T1 extends PipelineTransform<A, any>,
   1430                 T2 extends PipelineTransform<T1, any>,
   1431                 T3 extends PipelineTransform<T2, any>,
   1432                 B extends PipelineDestination<T3, any>,
   1433             >(
   1434                 source: A,
   1435                 transform1: T1,
   1436                 transform2: T2,
   1437                 transform3: T3,
   1438                 destination: B,
   1439                 options?: PipelineOptions,
   1440             ): PipelinePromise<B>;
   1441             function __promisify__<
   1442                 A extends PipelineSource<any>,
   1443                 T1 extends PipelineTransform<A, any>,
   1444                 T2 extends PipelineTransform<T1, any>,
   1445                 T3 extends PipelineTransform<T2, any>,
   1446                 T4 extends PipelineTransform<T3, any>,
   1447                 B extends PipelineDestination<T4, any>,
   1448             >(
   1449                 source: A,
   1450                 transform1: T1,
   1451                 transform2: T2,
   1452                 transform3: T3,
   1453                 transform4: T4,
   1454                 destination: B,
   1455                 options?: PipelineOptions,
   1456             ): PipelinePromise<B>;
   1457             function __promisify__(
   1458                 streams: ReadonlyArray<NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream>,
   1459                 options?: PipelineOptions,
   1460             ): Promise<void>;
   1461             function __promisify__(
   1462                 stream1: NodeJS.ReadableStream,
   1463                 stream2: NodeJS.ReadWriteStream | NodeJS.WritableStream,
   1464                 ...streams: Array<NodeJS.ReadWriteStream | NodeJS.WritableStream | PipelineOptions>
   1465             ): Promise<void>;
   1466         }
   1467         interface Pipe {
   1468             close(): void;
   1469             hasRef(): boolean;
   1470             ref(): void;
   1471             unref(): void;
   1472         }
   1473 
   1474         /**
   1475          * Returns whether the stream has encountered an error.
   1476          * @since v16.14.0
   1477          */
   1478         function isErrored(stream: Readable | Writable | NodeJS.ReadableStream | NodeJS.WritableStream): boolean;
   1479 
   1480         /**
   1481          * Returns whether the stream is readable.
   1482          * @since v16.14.0
   1483          */
   1484         function isReadable(stream: Readable | NodeJS.ReadableStream): boolean;
   1485 
   1486         const promises: typeof streamPromises;
   1487         const consumers: typeof streamConsumers;
   1488     }
   1489     export = internal;
   1490 }
   1491 declare module "node:stream" {
   1492     import stream = require("stream");
   1493     export = stream;
   1494 }
© notamitgamer • Site Built: 2026-07-21 13:58:23 UTC • git-mirror commit: 1037f62 [view raw info]
Originally created with stagit • modified by notamitgamer
Forked from github.com/notamitgamer/git-mirror