-
Notifications
You must be signed in to change notification settings - Fork 29.6k
/
stream.md
4525 lines (3566 loc) Β· 137 KB
/
stream.md
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Stream
<!--introduced_in=v0.10.0-->
> Stability: 2 - Stable
<!-- source_link=lib/stream.js -->
A stream is an abstract interface for working with streaming data in Node.js.
The `node:stream` module provides an API for implementing the stream interface.
There are many stream objects provided by Node.js. For instance, a
[request to an HTTP server][http-incoming-message] and [`process.stdout`][]
are both stream instances.
Streams can be readable, writable, or both. All streams are instances of
[`EventEmitter`][].
To access the `node:stream` module:
```js
const stream = require('node:stream');
```
The `node:stream` module is useful for creating new types of stream instances.
It is usually not necessary to use the `node:stream` module to consume streams.
## Organization of this document
This document contains two primary sections and a third section for notes. The
first section explains how to use existing streams within an application. The
second section explains how to create new types of streams.
## Types of streams
There are four fundamental stream types within Node.js:
* [`Writable`][]: streams to which data can be written (for example,
[`fs.createWriteStream()`][]).
* [`Readable`][]: streams from which data can be read (for example,
[`fs.createReadStream()`][]).
* [`Duplex`][]: streams that are both `Readable` and `Writable` (for example,
[`net.Socket`][]).
* [`Transform`][]: `Duplex` streams that can modify or transform the data as it
is written and read (for example, [`zlib.createDeflate()`][]).
Additionally, this module includes the utility functions
[`stream.pipeline()`][], [`stream.finished()`][], [`stream.Readable.from()`][]
and [`stream.addAbortSignal()`][].
### Streams Promises API
<!-- YAML
added: v15.0.0
-->
The `stream/promises` API provides an alternative set of asynchronous utility
functions for streams that return `Promise` objects rather than using
callbacks. The API is accessible via `require('node:stream/promises')`
or `require('node:stream').promises`.
### Object mode
All streams created by Node.js APIs operate exclusively on strings and `Buffer`
(or `Uint8Array`) objects. It is possible, however, for stream implementations
to work with other types of JavaScript values (with the exception of `null`,
which serves a special purpose within streams). Such streams are considered to
operate in "object mode".
Stream instances are switched into object mode using the `objectMode` option
when the stream is created. Attempting to switch an existing stream into
object mode is not safe.
### Buffering
<!--type=misc-->
Both [`Writable`][] and [`Readable`][] streams will store data in an internal
buffer.
The amount of data potentially buffered depends on the `highWaterMark` option
passed into the stream's constructor. For normal streams, the `highWaterMark`
option specifies a [total number of bytes][hwm-gotcha]. For streams operating
in object mode, the `highWaterMark` specifies a total number of objects.
Data is buffered in `Readable` streams when the implementation calls
[`stream.push(chunk)`][stream-push]. If the consumer of the Stream does not
call [`stream.read()`][stream-read], the data will sit in the internal
queue until it is consumed.
Once the total size of the internal read buffer reaches the threshold specified
by `highWaterMark`, the stream will temporarily stop reading data from the
underlying resource until the data currently buffered can be consumed (that is,
the stream will stop calling the internal [`readable._read()`][] method that is
used to fill the read buffer).
Data is buffered in `Writable` streams when the
[`writable.write(chunk)`][stream-write] method is called repeatedly. While the
total size of the internal write buffer is below the threshold set by
`highWaterMark`, calls to `writable.write()` will return `true`. Once
the size of the internal buffer reaches or exceeds the `highWaterMark`, `false`
will be returned.
A key goal of the `stream` API, particularly the [`stream.pipe()`][] method,
is to limit the buffering of data to acceptable levels such that sources and
destinations of differing speeds will not overwhelm the available memory.
The `highWaterMark` option is a threshold, not a limit: it dictates the amount
of data that a stream buffers before it stops asking for more data. It does not
enforce a strict memory limitation in general. Specific stream implementations
may choose to enforce stricter limits but doing so is optional.
Because [`Duplex`][] and [`Transform`][] streams are both `Readable` and
`Writable`, each maintains _two_ separate internal buffers used for reading and
writing, allowing each side to operate independently of the other while
maintaining an appropriate and efficient flow of data. For example,
[`net.Socket`][] instances are [`Duplex`][] streams whose `Readable` side allows
consumption of data received _from_ the socket and whose `Writable` side allows
writing data _to_ the socket. Because data may be written to the socket at a
faster or slower rate than data is received, each side should
operate (and buffer) independently of the other.
The mechanics of the internal buffering are an internal implementation detail
and may be changed at any time. However, for certain advanced implementations,
the internal buffers can be retrieved using `writable.writableBuffer` or
`readable.readableBuffer`. Use of these undocumented properties is discouraged.
## API for stream consumers
<!--type=misc-->
Almost all Node.js applications, no matter how simple, use streams in some
manner. The following is an example of using streams in a Node.js application
that implements an HTTP server:
```js
const http = require('node:http');
const server = http.createServer((req, res) => {
// `req` is an http.IncomingMessage, which is a readable stream.
// `res` is an http.ServerResponse, which is a writable stream.
let body = '';
// Get the data as utf8 strings.
// If an encoding is not set, Buffer objects will be received.
req.setEncoding('utf8');
// Readable streams emit 'data' events once a listener is added.
req.on('data', (chunk) => {
body += chunk;
});
// The 'end' event indicates that the entire body has been received.
req.on('end', () => {
try {
const data = JSON.parse(body);
// Write back something interesting to the user:
res.write(typeof data);
res.end();
} catch (er) {
// uh oh! bad json!
res.statusCode = 400;
return res.end(`error: ${er.message}`);
}
});
});
server.listen(1337);
// $ curl localhost:1337 -d "{}"
// object
// $ curl localhost:1337 -d "\"foo\""
// string
// $ curl localhost:1337 -d "not json"
// error: Unexpected token o in JSON at position 1
```
[`Writable`][] streams (such as `res` in the example) expose methods such as
`write()` and `end()` that are used to write data onto the stream.
[`Readable`][] streams use the [`EventEmitter`][] API for notifying application
code when data is available to be read off the stream. That available data can
be read from the stream in multiple ways.
Both [`Writable`][] and [`Readable`][] streams use the [`EventEmitter`][] API in
various ways to communicate the current state of the stream.
[`Duplex`][] and [`Transform`][] streams are both [`Writable`][] and
[`Readable`][].
Applications that are either writing data to or consuming data from a stream
are not required to implement the stream interfaces directly and will generally
have no reason to call `require('node:stream')`.
Developers wishing to implement new types of streams should refer to the
section [API for stream implementers][].
### Writable streams
Writable streams are an abstraction for a _destination_ to which data is
written.
Examples of [`Writable`][] streams include:
* [HTTP requests, on the client][]
* [HTTP responses, on the server][]
* [fs write streams][]
* [zlib streams][zlib]
* [crypto streams][crypto]
* [TCP sockets][]
* [child process stdin][]
* [`process.stdout`][], [`process.stderr`][]
Some of these examples are actually [`Duplex`][] streams that implement the
[`Writable`][] interface.
All [`Writable`][] streams implement the interface defined by the
`stream.Writable` class.
While specific instances of [`Writable`][] streams may differ in various ways,
all `Writable` streams follow the same fundamental usage pattern as illustrated
in the example below:
```js
const myStream = getWritableStreamSomehow();
myStream.write('some data');
myStream.write('some more data');
myStream.end('done writing data');
```
#### Class: `stream.Writable`
<!-- YAML
added: v0.9.4
-->
<!--type=class-->
##### Event: `'close'`
<!-- YAML
added: v0.9.4
changes:
- version: v10.0.0
pr-url: https://github.com/nodejs/node/pull/18438
description: Add `emitClose` option to specify if `'close'` is emitted on
destroy.
-->
The `'close'` event is emitted when the stream and any of its underlying
resources (a file descriptor, for example) have been closed. The event indicates
that no more events will be emitted, and no further computation will occur.
A [`Writable`][] stream will always emit the `'close'` event if it is
created with the `emitClose` option.
##### Event: `'drain'`
<!-- YAML
added: v0.9.4
-->
If a call to [`stream.write(chunk)`][stream-write] returns `false`, the
`'drain'` event will be emitted when it is appropriate to resume writing data
to the stream.
```js
// Write the data to the supplied writable stream one million times.
// Be attentive to back-pressure.
function writeOneMillionTimes(writer, data, encoding, callback) {
let i = 1000000;
write();
function write() {
let ok = true;
do {
i--;
if (i === 0) {
// Last time!
writer.write(data, encoding, callback);
} else {
// See if we should continue, or wait.
// Don't pass the callback, because we're not done yet.
ok = writer.write(data, encoding);
}
} while (i > 0 && ok);
if (i > 0) {
// Had to stop early!
// Write some more once it drains.
writer.once('drain', write);
}
}
}
```
##### Event: `'error'`
<!-- YAML
added: v0.9.4
-->
* {Error}
The `'error'` event is emitted if an error occurred while writing or piping
data. The listener callback is passed a single `Error` argument when called.
The stream is closed when the `'error'` event is emitted unless the
[`autoDestroy`][writable-new] option was set to `false` when creating the
stream.
After `'error'`, no further events other than `'close'` _should_ be emitted
(including `'error'` events).
##### Event: `'finish'`
<!-- YAML
added: v0.9.4
-->
The `'finish'` event is emitted after the [`stream.end()`][stream-end] method
has been called, and all data has been flushed to the underlying system.
```js
const writer = getWritableStreamSomehow();
for (let i = 0; i < 100; i++) {
writer.write(`hello, #${i}!\n`);
}
writer.on('finish', () => {
console.log('All writes are now complete.');
});
writer.end('This is the end\n');
```
##### Event: `'pipe'`
<!-- YAML
added: v0.9.4
-->
* `src` {stream.Readable} source stream that is piping to this writable
The `'pipe'` event is emitted when the [`stream.pipe()`][] method is called on
a readable stream, adding this writable to its set of destinations.
```js
const writer = getWritableStreamSomehow();
const reader = getReadableStreamSomehow();
writer.on('pipe', (src) => {
console.log('Something is piping into the writer.');
assert.equal(src, reader);
});
reader.pipe(writer);
```
##### Event: `'unpipe'`
<!-- YAML
added: v0.9.4
-->
* `src` {stream.Readable} The source stream that
[unpiped][`stream.unpipe()`] this writable
The `'unpipe'` event is emitted when the [`stream.unpipe()`][] method is called
on a [`Readable`][] stream, removing this [`Writable`][] from its set of
destinations.
This is also emitted in case this [`Writable`][] stream emits an error when a
[`Readable`][] stream pipes into it.
```js
const writer = getWritableStreamSomehow();
const reader = getReadableStreamSomehow();
writer.on('unpipe', (src) => {
console.log('Something has stopped piping into the writer.');
assert.equal(src, reader);
});
reader.pipe(writer);
reader.unpipe(writer);
```
##### `writable.cork()`
<!-- YAML
added: v0.11.2
-->
The `writable.cork()` method forces all written data to be buffered in memory.
The buffered data will be flushed when either the [`stream.uncork()`][] or
[`stream.end()`][stream-end] methods are called.
The primary intent of `writable.cork()` is to accommodate a situation in which
several small chunks are written to the stream in rapid succession. Instead of
immediately forwarding them to the underlying destination, `writable.cork()`
buffers all the chunks until `writable.uncork()` is called, which will pass them
all to `writable._writev()`, if present. This prevents a head-of-line blocking
situation where data is being buffered while waiting for the first small chunk
to be processed. However, use of `writable.cork()` without implementing
`writable._writev()` may have an adverse effect on throughput.
See also: [`writable.uncork()`][], [`writable._writev()`][stream-_writev].
##### `writable.destroy([error])`
<!-- YAML
added: v8.0.0
changes:
- version: v14.0.0
pr-url: https://github.com/nodejs/node/pull/29197
description: Work as a no-op on a stream that has already been destroyed.
-->
* `error` {Error} Optional, an error to emit with `'error'` event.
* Returns: {this}
Destroy the stream. Optionally emit an `'error'` event, and emit a `'close'`
event (unless `emitClose` is set to `false`). After this call, the writable
stream has ended and subsequent calls to `write()` or `end()` will result in
an `ERR_STREAM_DESTROYED` error.
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.
Use `end()` instead of destroy if data should flush before close, or wait for
the `'drain'` event before destroying the stream.
```cjs
const { Writable } = require('node:stream');
const myStream = new Writable();
const fooErr = new Error('foo error');
myStream.destroy(fooErr);
myStream.on('error', (fooErr) => console.error(fooErr.message)); // foo error
```
```cjs
const { Writable } = require('node:stream');
const myStream = new Writable();
myStream.destroy();
myStream.on('error', function wontHappen() {});
```
```cjs
const { Writable } = require('node:stream');
const myStream = new Writable();
myStream.destroy();
myStream.write('foo', (error) => console.error(error.code));
// ERR_STREAM_DESTROYED
```
Once `destroy()` has been called any further calls will be a no-op and no
further errors except from `_destroy()` may be emitted as `'error'`.
Implementors should not override this method,
but instead implement [`writable._destroy()`][writable-_destroy].
##### `writable.closed`
<!-- YAML
added: v18.0.0
-->
* {boolean}
Is `true` after `'close'` has been emitted.
##### `writable.destroyed`
<!-- YAML
added: v8.0.0
-->
* {boolean}
Is `true` after [`writable.destroy()`][writable-destroy] has been called.
```cjs
const { Writable } = require('node:stream');
const myStream = new Writable();
console.log(myStream.destroyed); // false
myStream.destroy();
console.log(myStream.destroyed); // true
```
##### `writable.end([chunk[, encoding]][, callback])`
<!-- YAML
added: v0.9.4
changes:
- version: v15.0.0
pr-url: https://github.com/nodejs/node/pull/34101
description: The `callback` is invoked before 'finish' or on error.
- version: v14.0.0
pr-url: https://github.com/nodejs/node/pull/29747
description: The `callback` is invoked if 'finish' or 'error' is emitted.
- version: v10.0.0
pr-url: https://github.com/nodejs/node/pull/18780
description: This method now returns a reference to `writable`.
- version: v8.0.0
pr-url: https://github.com/nodejs/node/pull/11608
description: The `chunk` argument can now be a `Uint8Array` instance.
-->
* `chunk` {string|Buffer|Uint8Array|any} Optional data to write. For streams
not operating in object mode, `chunk` must be a string, `Buffer` or
`Uint8Array`. For object mode streams, `chunk` may be any JavaScript value
other than `null`.
* `encoding` {string} The encoding if `chunk` is a string
* `callback` {Function} Callback for when the stream is finished.
* Returns: {this}
Calling the `writable.end()` method signals that no more data will be written
to the [`Writable`][]. The optional `chunk` and `encoding` arguments allow one
final additional chunk of data to be written immediately before closing the
stream.
Calling the [`stream.write()`][stream-write] method after calling
[`stream.end()`][stream-end] will raise an error.
```js
// Write 'hello, ' and then end with 'world!'.
const fs = require('node:fs');
const file = fs.createWriteStream('example.txt');
file.write('hello, ');
file.end('world!');
// Writing more now is not allowed!
```
##### `writable.setDefaultEncoding(encoding)`
<!-- YAML
added: v0.11.15
changes:
- version: v6.1.0
pr-url: https://github.com/nodejs/node/pull/5040
description: This method now returns a reference to `writable`.
-->
* `encoding` {string} The new default encoding
* Returns: {this}
The `writable.setDefaultEncoding()` method sets the default `encoding` for a
[`Writable`][] stream.
##### `writable.uncork()`
<!-- YAML
added: v0.11.2
-->
The `writable.uncork()` method flushes all data buffered since
[`stream.cork()`][] was called.
When using [`writable.cork()`][] and `writable.uncork()` to manage the buffering
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 loop phase.
```js
stream.cork();
stream.write('some ');
stream.write('data ');
process.nextTick(() => stream.uncork());
```
If the [`writable.cork()`][] method is called multiple times on a stream, the
same number of calls to `writable.uncork()` must be called to flush the buffered
data.
```js
stream.cork();
stream.write('some ');
stream.cork();
stream.write('data ');
process.nextTick(() => {
stream.uncork();
// The data will not be flushed until uncork() is called a second time.
stream.uncork();
});
```
See also: [`writable.cork()`][].
##### `writable.writable`
<!-- YAML
added: v11.4.0
-->
* {boolean}
Is `true` if it is safe to call [`writable.write()`][stream-write], which means
the stream has not been destroyed, errored or ended.
##### `writable.writableAborted`
<!-- YAML
added: v18.0.0
-->
> Stability: 1 - Experimental
* {boolean}
Returns whether the stream was destroyed or errored before emitting `'finish'`.
##### `writable.writableEnded`
<!-- YAML
added: v12.9.0
-->
* {boolean}
Is `true` after [`writable.end()`][] has been called. This property
does not indicate whether the data has been flushed, for this use
[`writable.writableFinished`][] instead.
##### `writable.writableCorked`
<!-- YAML
added:
- v13.2.0
- v12.16.0
-->
* {integer}
Number of times [`writable.uncork()`][stream-uncork] needs to be
called in order to fully uncork the stream.
##### `writable.errored`
<!-- YAML
added:
v18.0.0
-->
* {Error}
Returns error if the stream has been destroyed with an error.
##### `writable.writableFinished`
<!-- YAML
added: v12.6.0
-->
* {boolean}
Is set to `true` immediately before the [`'finish'`][] event is emitted.
##### `writable.writableHighWaterMark`
<!-- YAML
added: v9.3.0
-->
* {number}
Return the value of `highWaterMark` passed when creating this `Writable`.
##### `writable.writableLength`
<!-- YAML
added: v9.4.0
-->
* {number}
This property contains the number of bytes (or objects) in the queue
ready to be written. The value provides introspection data regarding
the status of the `highWaterMark`.
##### `writable.writableNeedDrain`
<!-- YAML
added:
- v15.2.0
- v14.17.0
-->
* {boolean}
Is `true` if the stream's buffer has been full and stream will emit `'drain'`.
##### `writable.writableObjectMode`
<!-- YAML
added: v12.3.0
-->
* {boolean}
Getter for the property `objectMode` of a given `Writable` stream.
##### `writable.write(chunk[, encoding][, callback])`
<!-- YAML
added: v0.9.4
changes:
- version: v8.0.0
pr-url: https://github.com/nodejs/node/pull/11608
description: The `chunk` argument can now be a `Uint8Array` instance.
- version: v6.0.0
pr-url: https://github.com/nodejs/node/pull/6170
description: Passing `null` as the `chunk` parameter will always be
considered invalid now, even in object mode.
-->
* `chunk` {string|Buffer|Uint8Array|any} Optional data to write. For streams
not operating in object mode, `chunk` must be a string, `Buffer` or
`Uint8Array`. For object mode streams, `chunk` may be any JavaScript value
other than `null`.
* `encoding` {string|null} The encoding, if `chunk` is a string. **Default:** `'utf8'`
* `callback` {Function} Callback for when this chunk of data is flushed.
* Returns: {boolean} `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`.
The `writable.write()` method writes some data to the stream, and calls the
supplied `callback` once the data has been fully handled. If an error
occurs, the `callback` will be called with the error as its
first argument. The `callback` is called asynchronously and before `'error'` is
emitted.
The return value is `true` if the internal buffer is less than the
`highWaterMark` configured when the stream was created after admitting `chunk`.
If `false` is returned, further attempts to write data to the stream should
stop until the [`'drain'`][] event is emitted.
While a stream is not draining, calls to `write()` will buffer `chunk`, and
return false. Once all currently buffered chunks are drained (accepted for
delivery by the operating system), the `'drain'` event will be emitted.
Once `write()` returns false, do not write more chunks
until the `'drain'` event is emitted. While calling `write()` on a stream that
is not draining is allowed, Node.js will buffer all written chunks until
maximum memory usage occurs, at which point it will abort unconditionally.
Even before it aborts, high memory usage will cause poor garbage collector
performance and high RSS (which is not typically released back to the system,
even after the memory is no longer required). Since TCP sockets may never
drain if the remote peer does not read the data, writing a socket that is
not draining may lead to a remotely exploitable vulnerability.
Writing data while the stream is not draining is particularly
problematic for a [`Transform`][], because the `Transform` streams are paused
by default until they are piped or a `'data'` or `'readable'` event handler
is added.
If the data to be written can be generated or fetched on demand, it is
recommended to encapsulate the logic into a [`Readable`][] and use
[`stream.pipe()`][]. However, if calling `write()` is preferred, it is
possible to respect backpressure and avoid memory issues using the
[`'drain'`][] event:
```js
function write(data, cb) {
if (!stream.write(data)) {
stream.once('drain', cb);
} else {
process.nextTick(cb);
}
}
// Wait for cb to be called before doing any other write.
write('hello', () => {
console.log('Write completed, do more writes now.');
});
```
A `Writable` stream in object mode will always ignore the `encoding` argument.
### Readable streams
Readable streams are an abstraction for a _source_ from which data is
consumed.
Examples of `Readable` streams include:
* [HTTP responses, on the client][http-incoming-message]
* [HTTP requests, on the server][http-incoming-message]
* [fs read streams][]
* [zlib streams][zlib]
* [crypto streams][crypto]
* [TCP sockets][]
* [child process stdout and stderr][]
* [`process.stdin`][]
All [`Readable`][] streams implement the interface defined by the
`stream.Readable` class.
#### Two reading modes
`Readable` streams effectively operate in one of two modes: flowing and
paused. These modes are separate from [object mode][object-mode].
A [`Readable`][] stream can be in object mode or not, regardless of whether
it is in flowing mode or paused mode.
* In flowing mode, data is read from the underlying system automatically
and provided to an application as quickly as possible using events via the
[`EventEmitter`][] interface.
* In paused mode, the [`stream.read()`][stream-read] method must be called
explicitly to read chunks of data from the stream.
All [`Readable`][] streams begin in paused mode but can be switched to flowing
mode in one of the following ways:
* Adding a [`'data'`][] event handler.
* Calling the [`stream.resume()`][stream-resume] method.
* Calling the [`stream.pipe()`][] method to send the data to a [`Writable`][].
The `Readable` can switch back to paused mode using one of the following:
* If there are no pipe destinations, by calling the
[`stream.pause()`][stream-pause] method.
* If there are pipe destinations, by removing all pipe destinations.
Multiple pipe destinations may be removed by calling the
[`stream.unpipe()`][] method.
The important concept to remember is that a `Readable` will not generate data
until a mechanism for either consuming or ignoring that data is provided. If
the consuming mechanism is disabled or taken away, the `Readable` will _attempt_
to stop generating the data.
For backward compatibility reasons, removing [`'data'`][] event handlers will
**not** automatically pause the stream. Also, if there are piped destinations,
then calling [`stream.pause()`][stream-pause] will not guarantee that the
stream will _remain_ paused once those destinations drain and ask for more data.
If a [`Readable`][] is switched into flowing mode and there are no consumers
available to handle the data, that data will be lost. This can occur, for
instance, when the `readable.resume()` method is called without a listener
attached to the `'data'` event, or when a `'data'` event handler is removed
from the stream.
Adding a [`'readable'`][] event handler automatically makes the stream
stop flowing, and the data has to be consumed via
[`readable.read()`][stream-read]. If the [`'readable'`][] event handler is
removed, then the stream will start flowing again if there is a
[`'data'`][] event handler.
#### Three states
The "two modes" of operation for a `Readable` stream are a simplified
abstraction for the more complicated internal state management that is happening
within the `Readable` stream implementation.
Specifically, at any given point in time, every `Readable` is in one of three
possible states:
* `readable.readableFlowing === null`
* `readable.readableFlowing === false`
* `readable.readableFlowing === true`
When `readable.readableFlowing` is `null`, no mechanism for consuming the
stream's data is provided. Therefore, the stream will not generate data.
While in this state, attaching a listener for the `'data'` event, calling the
`readable.pipe()` method, or calling the `readable.resume()` method will switch
`readable.readableFlowing` to `true`, causing the `Readable` to begin actively
emitting events as data is generated.
Calling `readable.pause()`, `readable.unpipe()`, or receiving backpressure
will cause the `readable.readableFlowing` to be set as `false`,
temporarily halting the flowing of events but _not_ halting the generation of
data. While in this state, attaching a listener for the `'data'` event
will not switch `readable.readableFlowing` to `true`.
```js
const { PassThrough, Writable } = require('node:stream');
const pass = new PassThrough();
const writable = new Writable();
pass.pipe(writable);
pass.unpipe(writable);
// readableFlowing is now false.
pass.on('data', (chunk) => { console.log(chunk.toString()); });
pass.write('ok'); // Will not emit 'data'.
pass.resume(); // Must be called to make stream emit 'data'.
```
While `readable.readableFlowing` is `false`, data may be accumulating
within the stream's internal buffer.
#### Choose one API style
The `Readable` stream API evolved across multiple Node.js versions and provides
multiple methods of consuming stream data. In general, developers should choose
_one_ of the methods of consuming data and _should never_ use multiple methods
to consume data from a single stream. Specifically, using a combination
of `on('data')`, `on('readable')`, `pipe()`, or async iterators could
lead to unintuitive behavior.
#### Class: `stream.Readable`
<!-- YAML
added: v0.9.4
-->
<!--type=class-->
##### Event: `'close'`
<!-- YAML
added: v0.9.4
changes:
- version: v10.0.0
pr-url: https://github.com/nodejs/node/pull/18438
description: Add `emitClose` option to specify if `'close'` is emitted on
destroy.
-->
The `'close'` event is emitted when the stream and any of its underlying
resources (a file descriptor, for example) have been closed. The event indicates
that no more events will be emitted, and no further computation will occur.
A [`Readable`][] stream will always emit the `'close'` event if it is
created with the `emitClose` option.
##### Event: `'data'`
<!-- YAML
added: v0.9.4
-->
* `chunk` {Buffer|string|any} The chunk of data. For streams that are not
operating in object mode, the chunk will be either a string or `Buffer`.
For streams that are in object mode, the chunk can be any JavaScript value
other than `null`.
The `'data'` event is emitted whenever the stream is relinquishing ownership of
a chunk of data to a consumer. This may occur whenever the stream is switched
in flowing mode by calling `readable.pipe()`, `readable.resume()`, or by
attaching a listener callback to the `'data'` event. The `'data'` event will
also be emitted whenever the `readable.read()` method is called and a chunk of
data is available to be returned.
Attaching a `'data'` event listener to a stream that has not been explicitly
paused will switch the stream into flowing mode. Data will then be passed as
soon as it is available.
The listener callback will be passed the chunk of data as a string if a default
encoding has been specified for the stream using the
`readable.setEncoding()` method; otherwise the data will be passed as a
`Buffer`.
```js
const readable = getReadableStreamSomehow();
readable.on('data', (chunk) => {
console.log(`Received ${chunk.length} bytes of data.`);
});
```
##### Event: `'end'`
<!-- YAML
added: v0.9.4
-->
The `'end'` event is emitted when there is no more data to be consumed from
the stream.
The `'end'` event **will not be emitted** unless the data is completely
consumed. This can be accomplished by switching the stream into flowing mode,
or by calling [`stream.read()`][stream-read] repeatedly until all data has been
consumed.
```js
const readable = getReadableStreamSomehow();
readable.on('data', (chunk) => {
console.log(`Received ${chunk.length} bytes of data.`);
});
readable.on('end', () => {
console.log('There will be no more data.');
});
```
##### Event: `'error'`
<!-- YAML
added: v0.9.4
-->
* {Error}
The `'error'` event may be emitted by a `Readable` implementation at any time.
Typically, this may occur if the underlying stream is unable to generate data
due to an underlying internal failure, or when a stream implementation attempts
to push an invalid chunk of data.
The listener callback will be passed a single `Error` object.
##### Event: `'pause'`
<!-- YAML