3671edf95424a3ad4c339aade002049a96b1c8d429be2edb6da2dccdc193f22c942a9ef42dafae3cf7b62356742bdb7dacebfa33462374fc34e2b7a4cf4427 83 KB

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