98ca9786d4197cdddfd7f15be06c6d37a08a619ffaf22a291087f9bdf9e9c0a5795af401c80807d19ecbca5c53c42835a9dd0b1469409b25475a09ad4ac93d 83 KB

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