-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathstream.html
More file actions
2353 lines (2241 loc) · 165 KB
/
stream.html
File metadata and controls
2353 lines (2241 loc) · 165 KB
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
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Stream | Node.js v12.0.0 Documentation</title>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Lato:400,700,400italic">
<link rel="stylesheet" href="assets/style.css">
<link rel="stylesheet" href="assets/hljs.css">
<link rel="canonical" href="https://nodejs.org/api/stream.html">
</head>
<body class="alt apidoc" id="api-section-stream">
<div id="content" class="clearfix">
<div id="column2" class="interior">
<div id="intro" class="interior">
<a href="/" title="Go back to the home page">
Node.js
</a>
</div>
<ul>
<li><a href="documentation.html" class="nav-documentation">About these Docs</a></li>
<li><a href="synopsis.html" class="nav-synopsis">Usage & Example</a></li>
</ul>
<div class="line"></div>
<ul>
<li><a href="assert.html" class="nav-assert">Assertion Testing</a></li>
<li><a href="async_hooks.html" class="nav-async_hooks">Async Hooks</a></li>
<li><a href="buffer.html" class="nav-buffer">Buffer</a></li>
<li><a href="addons.html" class="nav-addons">C++ Addons</a></li>
<li><a href="n-api.html" class="nav-n-api">C/C++ Addons - N-API</a></li>
<li><a href="child_process.html" class="nav-child_process">Child Processes</a></li>
<li><a href="cluster.html" class="nav-cluster">Cluster</a></li>
<li><a href="cli.html" class="nav-cli">Command Line Options</a></li>
<li><a href="console.html" class="nav-console">Console</a></li>
<li><a href="crypto.html" class="nav-crypto">Crypto</a></li>
<li><a href="debugger.html" class="nav-debugger">Debugger</a></li>
<li><a href="deprecations.html" class="nav-deprecations">Deprecated APIs</a></li>
<li><a href="dns.html" class="nav-dns">DNS</a></li>
<li><a href="domain.html" class="nav-domain">Domain</a></li>
<li><a href="esm.html" class="nav-esm">ECMAScript Modules</a></li>
<li><a href="errors.html" class="nav-errors">Errors</a></li>
<li><a href="events.html" class="nav-events">Events</a></li>
<li><a href="fs.html" class="nav-fs">File System</a></li>
<li><a href="globals.html" class="nav-globals">Globals</a></li>
<li><a href="http.html" class="nav-http">HTTP</a></li>
<li><a href="http2.html" class="nav-http2">HTTP/2</a></li>
<li><a href="https.html" class="nav-https">HTTPS</a></li>
<li><a href="inspector.html" class="nav-inspector">Inspector</a></li>
<li><a href="intl.html" class="nav-intl">Internationalization</a></li>
<li><a href="modules.html" class="nav-modules">Modules</a></li>
<li><a href="net.html" class="nav-net">Net</a></li>
<li><a href="os.html" class="nav-os">OS</a></li>
<li><a href="path.html" class="nav-path">Path</a></li>
<li><a href="perf_hooks.html" class="nav-perf_hooks">Performance Hooks</a></li>
<li><a href="process.html" class="nav-process">Process</a></li>
<li><a href="punycode.html" class="nav-punycode">Punycode</a></li>
<li><a href="querystring.html" class="nav-querystring">Query Strings</a></li>
<li><a href="readline.html" class="nav-readline">Readline</a></li>
<li><a href="repl.html" class="nav-repl">REPL</a></li>
<li><a href="stream.html" class="nav-stream active">Stream</a></li>
<li><a href="string_decoder.html" class="nav-string_decoder">String Decoder</a></li>
<li><a href="timers.html" class="nav-timers">Timers</a></li>
<li><a href="tls.html" class="nav-tls">TLS/SSL</a></li>
<li><a href="tracing.html" class="nav-tracing">Trace Events</a></li>
<li><a href="tty.html" class="nav-tty">TTY</a></li>
<li><a href="dgram.html" class="nav-dgram">UDP/Datagram</a></li>
<li><a href="url.html" class="nav-url">URL</a></li>
<li><a href="util.html" class="nav-util">Utilities</a></li>
<li><a href="v8.html" class="nav-v8">V8</a></li>
<li><a href="vm.html" class="nav-vm">VM</a></li>
<li><a href="worker_threads.html" class="nav-worker_threads">Worker Threads</a></li>
<li><a href="zlib.html" class="nav-zlib">ZLIB</a></li>
</ul>
<div class="line"></div>
<ul>
<li><a href="https://github.com/nodejs/node" class="nav-https-github-com-nodejs-node">GitHub Repo & Issue Tracker</a></li>
</ul>
</div>
<div id="column1" data-id="stream" class="interior">
<header>
<h1>Node.js v12.0.0 Documentation</h1>
<div id="gtoc">
<ul>
<li>
<a href="index.html" name="toc">Index</a>
</li>
<li>
<a href="all.html">View on single page</a>
</li>
<li>
<a href="stream.json">View as JSON</a>
</li>
<li class="version-picker">
<a href="#">View another version <span>▼</span></a>
<ol class="version-picker"><li><a href="https://nodejs.org/docs/latest-v11.x/api/stream.html">11.x</a></li>
<li><a href="https://nodejs.org/docs/latest-v10.x/api/stream.html">10.x <b>LTS</b></a></li>
<li><a href="https://nodejs.org/docs/latest-v9.x/api/stream.html">9.x</a></li>
<li><a href="https://nodejs.org/docs/latest-v8.x/api/stream.html">8.x <b>LTS</b></a></li>
<li><a href="https://nodejs.org/docs/latest-v7.x/api/stream.html">7.x</a></li>
<li><a href="https://nodejs.org/docs/latest-v6.x/api/stream.html">6.x <b>LTS</b></a></li>
<li><a href="https://nodejs.org/docs/latest-v5.x/api/stream.html">5.x</a></li>
<li><a href="https://nodejs.org/docs/latest-v4.x/api/stream.html">4.x</a></li>
<li><a href="https://nodejs.org/docs/latest-v0.12.x/api/stream.html">0.12.x</a></li>
<li><a href="https://nodejs.org/docs/latest-v0.10.x/api/stream.html">0.10.x</a></li></ol>
</li>
<li class="edit_on_github"><a href="https://github.com/nodejs/node/edit/master/doc/api/stream.md"><span class="github_icon"><svg height="16" width="16" viewBox="0 0 16.1 16.1" fill="currentColor"><path d="M8 0a8 8 0 0 0-2.5 15.6c.4 0 .5-.2.5-.4v-1.5c-2 .4-2.5-.5-2.7-1 0-.1-.5-.9-.8-1-.3-.2-.7-.6 0-.6.6 0 1 .6 1.2.8.7 1.2 1.9 1 2.4.7 0-.5.2-.9.5-1-1.8-.3-3.7-1-3.7-4 0-.9.3-1.6.8-2.2 0-.2-.3-1 .1-2 0 0 .7-.3 2.2.7a7.4 7.4 0 0 1 4 0c1.5-1 2.2-.8 2.2-.8.5 1.1.2 2 .1 2.1.5.6.8 1.3.8 2.2 0 3-1.9 3.7-3.6 4 .3.2.5.7.5 1.4v2.2c0 .2.1.5.5.4A8 8 0 0 0 16 8a8 8 0 0 0-8-8z"/></svg></span>Edit on GitHub</a></li>
</ul>
</div>
<hr>
</header>
<div id="toc">
<h2>Table of Contents</h2>
<ul>
<li>
<p><span class="stability_2"><a href="#stream_stream">Stream</a></span></p>
<ul>
<li><a href="#stream_organization_of_this_document">Organization of this Document</a></li>
<li>
<p><a href="#stream_types_of_streams">Types of Streams</a></p>
<ul>
<li><a href="#stream_object_mode">Object Mode</a></li>
<li><a href="#stream_buffering">Buffering</a></li>
</ul>
</li>
<li>
<p><a href="#stream_api_for_stream_consumers">API for Stream Consumers</a></p>
<ul>
<li>
<p><a href="#stream_writable_streams">Writable Streams</a></p>
<ul>
<li>
<p><a href="#stream_class_stream_writable">Class: stream.Writable</a></p>
<ul>
<li><a href="#stream_event_close">Event: 'close'</a></li>
<li><a href="#stream_event_drain">Event: 'drain'</a></li>
<li><a href="#stream_event_error">Event: 'error'</a></li>
<li><a href="#stream_event_finish">Event: 'finish'</a></li>
<li><a href="#stream_event_pipe">Event: 'pipe'</a></li>
<li><a href="#stream_event_unpipe">Event: 'unpipe'</a></li>
<li><a href="#stream_writable_cork">writable.cork()</a></li>
<li><a href="#stream_writable_destroy_error">writable.destroy([error])</a></li>
<li><a href="#stream_writable_end_chunk_encoding_callback">writable.end([chunk][, encoding][, callback])</a></li>
<li><a href="#stream_writable_setdefaultencoding_encoding">writable.setDefaultEncoding(encoding)</a></li>
<li><a href="#stream_writable_uncork">writable.uncork()</a></li>
<li><a href="#stream_writable_writablehighwatermark">writable.writableHighWaterMark</a></li>
<li><a href="#stream_writable_writablelength">writable.writableLength</a></li>
<li><a href="#stream_writable_write_chunk_encoding_callback">writable.write(chunk[, encoding][, callback])</a></li>
</ul>
</li>
</ul>
</li>
<li>
<p><a href="#stream_readable_streams">Readable Streams</a></p>
<ul>
<li><a href="#stream_two_reading_modes">Two Reading Modes</a></li>
<li><a href="#stream_three_states">Three States</a></li>
<li><a href="#stream_choose_one_api_style">Choose One API Style</a></li>
<li>
<p><a href="#stream_class_stream_readable">Class: stream.Readable</a></p>
<ul>
<li><a href="#stream_event_close_1">Event: 'close'</a></li>
<li><a href="#stream_event_data">Event: 'data'</a></li>
<li><a href="#stream_event_end">Event: 'end'</a></li>
<li><a href="#stream_event_error_1">Event: 'error'</a></li>
<li><a href="#stream_event_readable">Event: 'readable'</a></li>
<li><a href="#stream_readable_destroy_error">readable.destroy([error])</a></li>
<li><a href="#stream_readable_ispaused">readable.isPaused()</a></li>
<li><a href="#stream_readable_pause">readable.pause()</a></li>
<li><a href="#stream_readable_pipe_destination_options">readable.pipe(destination[, options])</a></li>
<li><a href="#stream_readable_read_size">readable.read([size])</a></li>
<li><a href="#stream_readable_readablehighwatermark">readable.readableHighWaterMark</a></li>
<li><a href="#stream_readable_readablelength">readable.readableLength</a></li>
<li><a href="#stream_readable_resume">readable.resume()</a></li>
<li><a href="#stream_readable_setencoding_encoding">readable.setEncoding(encoding)</a></li>
<li><a href="#stream_readable_unpipe_destination">readable.unpipe([destination])</a></li>
<li><a href="#stream_readable_unshift_chunk">readable.unshift(chunk)</a></li>
<li><a href="#stream_readable_wrap_stream">readable.wrap(stream)</a></li>
<li><span class="stability_1"><a href="#stream_readable_symbol_asynciterator">readable[Symbol.asyncIterator]()</a></span></li>
</ul>
</li>
</ul>
</li>
<li>
<p><a href="#stream_duplex_and_transform_streams">Duplex and Transform Streams</a></p>
<ul>
<li><a href="#stream_class_stream_duplex">Class: stream.Duplex</a></li>
<li>
<p><a href="#stream_class_stream_transform">Class: stream.Transform</a></p>
<ul>
<li><a href="#stream_transform_destroy_error">transform.destroy([error])</a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#stream_stream_finished_stream_options_callback">stream.finished(stream[, options], callback)</a></li>
<li><a href="#stream_stream_pipeline_streams_callback">stream.pipeline(...streams, callback)</a></li>
</ul>
</li>
<li>
<p><a href="#stream_api_for_stream_implementers">API for Stream Implementers</a></p>
<ul>
<li><a href="#stream_simplified_construction">Simplified Construction</a></li>
<li>
<p><a href="#stream_implementing_a_writable_stream">Implementing a Writable Stream</a></p>
<ul>
<li><a href="#stream_constructor_new_stream_writable_options">Constructor: new stream.Writable([options])</a></li>
<li><a href="#stream_writable_write_chunk_encoding_callback_1">writable._write(chunk, encoding, callback)</a></li>
<li><a href="#stream_writable_writev_chunks_callback">writable._writev(chunks, callback)</a></li>
<li><a href="#stream_writable_destroy_err_callback">writable._destroy(err, callback)</a></li>
<li><a href="#stream_writable_final_callback">writable._final(callback)</a></li>
<li><a href="#stream_errors_while_writing">Errors While Writing</a></li>
<li><a href="#stream_an_example_writable_stream">An Example Writable Stream</a></li>
<li><a href="#stream_decoding_buffers_in_a_writable_stream">Decoding buffers in a Writable Stream</a></li>
</ul>
</li>
<li>
<p><a href="#stream_implementing_a_readable_stream">Implementing a Readable Stream</a></p>
<ul>
<li><a href="#stream_new_stream_readable_options">new stream.Readable([options])</a></li>
<li><a href="#stream_readable_read_size_1">readable._read(size)</a></li>
<li><a href="#stream_readable_destroy_err_callback">readable._destroy(err, callback)</a></li>
<li><a href="#stream_readable_push_chunk_encoding">readable.push(chunk[, encoding])</a></li>
<li><a href="#stream_errors_while_reading">Errors While Reading</a></li>
<li><a href="#stream_an_example_counting_stream">An Example Counting Stream</a></li>
</ul>
</li>
<li>
<p><a href="#stream_implementing_a_duplex_stream">Implementing a Duplex Stream</a></p>
<ul>
<li><a href="#stream_new_stream_duplex_options">new stream.Duplex(options)</a></li>
<li><a href="#stream_an_example_duplex_stream">An Example Duplex Stream</a></li>
<li><a href="#stream_object_mode_duplex_streams">Object Mode Duplex Streams</a></li>
</ul>
</li>
<li>
<p><a href="#stream_implementing_a_transform_stream">Implementing a Transform Stream</a></p>
<ul>
<li><a href="#stream_new_stream_transform_options">new stream.Transform([options])</a></li>
<li><a href="#stream_events_finish_and_end">Events: 'finish' and 'end'</a></li>
<li><a href="#stream_transform_flush_callback">transform._flush(callback)</a></li>
<li><a href="#stream_transform_transform_chunk_encoding_callback">transform._transform(chunk, encoding, callback)</a></li>
<li><a href="#stream_class_stream_passthrough">Class: stream.PassThrough</a></li>
</ul>
</li>
</ul>
</li>
<li>
<p><a href="#stream_additional_notes">Additional Notes</a></p>
<ul>
<li><a href="#stream_compatibility_with_older_node_js_versions">Compatibility with Older Node.js Versions</a></li>
<li><a href="#stream_readable_read_0"><code>readable.read(0)</code></a></li>
<li><a href="#stream_readable_push"><code>readable.push('')</code></a></li>
<li><a href="#stream_highwatermark_discrepancy_after_calling_readable_setencoding"><code>highWaterMark</code> discrepancy after calling <code>readable.setEncoding()</code></a></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div id="apicontent">
<h1>Stream<a class="srclink" href="https://github.com/runkitdev/node/blob/cf1ce2bcc1a88ef6ff1bf745a19913a69607fb02/lib/stream.js#L30">[src]</a><span><a class="mark" href="#stream_stream" id="stream_stream">#</a></span></h1>
<p></p><div class="api_stability api_stability_2"><a href="documentation.html#documentation_stability_index">Stability: 2</a> - Stable</div><p></p>
<p>A stream is an abstract interface for working with streaming data in Node.js.
The <code>stream</code> module provides a base API that makes it easy to build objects
that implement the stream interface.</p>
<p>There are many stream objects provided by Node.js. For instance, a
<a href="http.html#http_class_http_incomingmessage">request to an HTTP server</a> and <a href="process.html#process_process_stdout"><code>process.stdout</code></a>
are both stream instances.</p>
<p>Streams can be readable, writable, or both. All streams are instances of
<a href="events.html#events_class_eventemitter"><code>EventEmitter</code></a>.</p>
<p>The <code>stream</code> module can be accessed using:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> stream = <span class="hljs-built_in">require</span>(<span class="hljs-string">'stream'</span>);</code></pre>
<p>While it is important to understand how streams work, the <code>stream</code> module itself
is most useful for developers that are creating new types of stream instances.
Developers who are primarily <em>consuming</em> stream objects will rarely need to use
the <code>stream</code> module directly.</p>
<h2>Organization of this Document<span><a class="mark" href="#stream_organization_of_this_document" id="stream_organization_of_this_document">#</a></span></h2>
<p>This document is divided into two primary sections with a third section for
additional notes. The first section explains the elements of the stream API that
are required to <em>use</em> streams within an application. The second section explains
the elements of the API that are required to <em>implement</em> new types of streams.</p>
<h2>Types of Streams<span><a class="mark" href="#stream_types_of_streams" id="stream_types_of_streams">#</a></span></h2>
<p>There are four fundamental stream types within Node.js:</p>
<ul>
<li><a href="#stream_class_stream_writable"><code>Writable</code></a> - streams to which data can be written (for example,
<a href="fs.html#fs_fs_createwritestream_path_options"><code>fs.createWriteStream()</code></a>).</li>
<li><a href="#stream_class_stream_readable"><code>Readable</code></a> - streams from which data can be read (for example,
<a href="fs.html#fs_fs_createreadstream_path_options"><code>fs.createReadStream()</code></a>).</li>
<li><a href="#stream_class_stream_duplex"><code>Duplex</code></a> - streams that are both <code>Readable</code> and <code>Writable</code> (for example,
<a href="net.html#net_class_net_socket"><code>net.Socket</code></a>).</li>
<li><a href="#stream_class_stream_transform"><code>Transform</code></a> - <code>Duplex</code> streams that can modify or transform the data as it
is written and read (for example, <a href="zlib.html#zlib_zlib_createdeflate_options"><code>zlib.createDeflate()</code></a>).</li>
</ul>
<p>Additionally, this module includes the utility functions <a href="#stream_stream_pipeline_streams_callback">pipeline</a> and
<a href="#stream_stream_finished_stream_options_callback">finished</a>.</p>
<h3>Object Mode<span><a class="mark" href="#stream_object_mode" id="stream_object_mode">#</a></span></h3>
<p>All streams created by Node.js APIs operate exclusively on strings and <code>Buffer</code>
(or <code>Uint8Array</code>) objects. It is possible, however, for stream implementations
to work with other types of JavaScript values (with the exception of <code>null</code>,
which serves a special purpose within streams). Such streams are considered to
operate in "object mode".</p>
<p>Stream instances are switched into object mode using the <code>objectMode</code> option
when the stream is created. Attempting to switch an existing stream into
object mode is not safe.</p>
<h3>Buffering<span><a class="mark" href="#stream_buffering" id="stream_buffering">#</a></span></h3>
<p>Both <a href="#stream_class_stream_writable"><code>Writable</code></a> and <a href="#stream_class_stream_readable"><code>Readable</code></a> streams will store data in an internal
buffer that can be retrieved using <code>writable.writableBuffer</code> or
<code>readable.readableBuffer</code>, respectively.</p>
<p>The amount of data potentially buffered depends on the <code>highWaterMark</code> option
passed into the stream's constructor. For normal streams, the <code>highWaterMark</code>
option specifies a <a href="#stream_highwatermark_discrepancy_after_calling_readable_setencoding">total number of bytes</a>. For streams operating
in object mode, the <code>highWaterMark</code> specifies a total number of objects.</p>
<p>Data is buffered in <code>Readable</code> streams when the implementation calls
<a href="#stream_readable_push_chunk_encoding"><code>stream.push(chunk)</code></a>. If the consumer of the Stream does not
call <a href="#stream_readable_read_size"><code>stream.read()</code></a>, the data will sit in the internal
queue until it is consumed.</p>
<p>Once the total size of the internal read buffer reaches the threshold specified
by <code>highWaterMark</code>, 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 <code>readable._read()</code> method that is
used to fill the read buffer).</p>
<p>Data is buffered in <code>Writable</code> streams when the
<a href="#stream_writable_write_chunk_encoding_callback"><code>writable.write(chunk)</code></a> method is called repeatedly. While the
total size of the internal write buffer is below the threshold set by
<code>highWaterMark</code>, calls to <code>writable.write()</code> will return <code>true</code>. Once
the size of the internal buffer reaches or exceeds the <code>highWaterMark</code>, <code>false</code>
will be returned.</p>
<p>A key goal of the <code>stream</code> API, particularly the <a href="#stream_readable_pipe_destination_options"><code>stream.pipe()</code></a> 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.</p>
<p>Because <a href="#stream_class_stream_duplex"><code>Duplex</code></a> and <a href="#stream_class_stream_transform"><code>Transform</code></a> streams are both <code>Readable</code> and
<code>Writable</code>, each maintains <em>two</em> 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,
<a href="net.html#net_class_net_socket"><code>net.Socket</code></a> instances are <a href="#stream_class_stream_duplex"><code>Duplex</code></a> streams whose <code>Readable</code> side allows
consumption of data received <em>from</em> the socket and whose <code>Writable</code> side allows
writing data <em>to</em> the socket. Because data may be written to the socket at a
faster or slower rate than data is received, it is important for each side to
operate (and buffer) independently of the other.</p>
<h2>API for Stream Consumers<span><a class="mark" href="#stream_api_for_stream_consumers" id="stream_api_for_stream_consumers">#</a></span></h2>
<p>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:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> http = <span class="hljs-built_in">require</span>(<span class="hljs-string">'http'</span>);
<span class="hljs-keyword">const</span> server = http.createServer(<span class="hljs-function">(<span class="hljs-params">req, res</span>) =></span> {
<span class="hljs-comment">// req is an http.IncomingMessage, which is a Readable Stream</span>
<span class="hljs-comment">// res is an http.ServerResponse, which is a Writable Stream</span>
<span class="hljs-keyword">let</span> body = <span class="hljs-string">''</span>;
<span class="hljs-comment">// Get the data as utf8 strings.</span>
<span class="hljs-comment">// If an encoding is not set, Buffer objects will be received.</span>
req.setEncoding(<span class="hljs-string">'utf8'</span>);
<span class="hljs-comment">// Readable streams emit 'data' events once a listener is added</span>
req.on(<span class="hljs-string">'data'</span>, (chunk) => {
body += chunk;
});
<span class="hljs-comment">// the 'end' event indicates that the entire body has been received</span>
req.on(<span class="hljs-string">'end'</span>, () => {
<span class="hljs-keyword">try</span> {
<span class="hljs-keyword">const</span> data = <span class="hljs-built_in">JSON</span>.parse(body);
<span class="hljs-comment">// write back something interesting to the user:</span>
res.write(<span class="hljs-keyword">typeof</span> data);
res.end();
} <span class="hljs-keyword">catch</span> (er) {
<span class="hljs-comment">// uh oh! bad json!</span>
res.statusCode = <span class="hljs-number">400</span>;
<span class="hljs-keyword">return</span> res.end(<span class="hljs-string">`error: <span class="hljs-subst">${er.message}</span>`</span>);
}
});
});
server.listen(<span class="hljs-number">1337</span>);
<span class="hljs-comment">// $ curl localhost:1337 -d "{}"</span>
<span class="hljs-comment">// object</span>
<span class="hljs-comment">// $ curl localhost:1337 -d "\"foo\""</span>
<span class="hljs-comment">// string</span>
<span class="hljs-comment">// $ curl localhost:1337 -d "not json"</span>
<span class="hljs-comment">// error: Unexpected token o in JSON at position 1</span></code></pre>
<p><a href="#stream_class_stream_writable"><code>Writable</code></a> streams (such as <code>res</code> in the example) expose methods such as
<code>write()</code> and <code>end()</code> that are used to write data onto the stream.</p>
<p><a href="#stream_class_stream_readable"><code>Readable</code></a> streams use the <a href="events.html#events_class_eventemitter"><code>EventEmitter</code></a> 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.</p>
<p>Both <a href="#stream_class_stream_writable"><code>Writable</code></a> and <a href="#stream_class_stream_readable"><code>Readable</code></a> streams use the <a href="events.html#events_class_eventemitter"><code>EventEmitter</code></a> API in
various ways to communicate the current state of the stream.</p>
<p><a href="#stream_class_stream_duplex"><code>Duplex</code></a> and <a href="#stream_class_stream_transform"><code>Transform</code></a> streams are both <a href="#stream_class_stream_writable"><code>Writable</code></a> and
<a href="#stream_class_stream_readable"><code>Readable</code></a>.</p>
<p>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 <code>require('stream')</code>.</p>
<p>Developers wishing to implement new types of streams should refer to the
section <a href="#stream_api_for_stream_implementers">API for Stream Implementers</a>.</p>
<h3>Writable Streams<span><a class="mark" href="#stream_writable_streams" id="stream_writable_streams">#</a></span></h3>
<p>Writable streams are an abstraction for a <em>destination</em> to which data is
written.</p>
<p>Examples of <a href="#stream_class_stream_writable"><code>Writable</code></a> streams include:</p>
<ul>
<li><a href="http.html#http_class_http_clientrequest">HTTP requests, on the client</a></li>
<li><a href="http.html#http_class_http_serverresponse">HTTP responses, on the server</a></li>
<li><a href="fs.html#fs_class_fs_writestream">fs write streams</a></li>
<li><a href="zlib.html">zlib streams</a></li>
<li><a href="crypto.html">crypto streams</a></li>
<li><a href="net.html#net_class_net_socket">TCP sockets</a></li>
<li><a href="child_process.html#child_process_subprocess_stdin">child process stdin</a></li>
<li><a href="process.html#process_process_stdout"><code>process.stdout</code></a>, <a href="process.html#process_process_stderr"><code>process.stderr</code></a></li>
</ul>
<p>Some of these examples are actually <a href="#stream_class_stream_duplex"><code>Duplex</code></a> streams that implement the
<a href="#stream_class_stream_writable"><code>Writable</code></a> interface.</p>
<p>All <a href="#stream_class_stream_writable"><code>Writable</code></a> streams implement the interface defined by the
<code>stream.Writable</code> class.</p>
<p>While specific instances of <a href="#stream_class_stream_writable"><code>Writable</code></a> streams may differ in various ways,
all <code>Writable</code> streams follow the same fundamental usage pattern as illustrated
in the example below:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> myStream = getWritableStreamSomehow();
myStream.write(<span class="hljs-string">'some data'</span>);
myStream.write(<span class="hljs-string">'some more data'</span>);
myStream.end(<span class="hljs-string">'done writing data'</span>);</code></pre>
<h4>Class: stream.Writable<span><a class="mark" href="#stream_class_stream_writable" id="stream_class_stream_writable">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v0.9.4</span>
</div>
<h5>Event: 'close'<span><a class="mark" href="#stream_event_close" id="stream_event_close">#</a></span></h5>
<div class="api_metadata">
<span>Added in: v0.9.4</span>
</div>
<p>The <code>'close'</code> 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.</p>
<p>Not all <code>Writable</code> streams will emit the <code>'close'</code> event.</p>
<h5>Event: 'drain'<span><a class="mark" href="#stream_event_drain" id="stream_event_drain">#</a></span></h5>
<div class="api_metadata">
<span>Added in: v0.9.4</span>
</div>
<p>If a call to <a href="#stream_writable_write_chunk_encoding_callback"><code>stream.write(chunk)</code></a> returns <code>false</code>, the
<code>'drain'</code> event will be emitted when it is appropriate to resume writing data
to the stream.</p>
<pre><code class="language-js"><span class="hljs-comment">// Write the data to the supplied writable stream one million times.</span>
<span class="hljs-comment">// Be attentive to back-pressure.</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">writeOneMillionTimes</span>(<span class="hljs-params">writer, data, encoding, callback</span>) </span>{
<span class="hljs-keyword">let</span> i = <span class="hljs-number">1000000</span>;
write();
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">write</span>(<span class="hljs-params"></span>) </span>{
<span class="hljs-keyword">let</span> ok = <span class="hljs-literal">true</span>;
<span class="hljs-keyword">do</span> {
i--;
<span class="hljs-keyword">if</span> (i === <span class="hljs-number">0</span>) {
<span class="hljs-comment">// last time!</span>
writer.write(data, encoding, callback);
} <span class="hljs-keyword">else</span> {
<span class="hljs-comment">// see if we should continue, or wait</span>
<span class="hljs-comment">// don't pass the callback, because we're not done yet.</span>
ok = writer.write(data, encoding);
}
} <span class="hljs-keyword">while</span> (i > <span class="hljs-number">0</span> && ok);
<span class="hljs-keyword">if</span> (i > <span class="hljs-number">0</span>) {
<span class="hljs-comment">// had to stop early!</span>
<span class="hljs-comment">// write some more once it drains</span>
writer.once(<span class="hljs-string">'drain'</span>, write);
}
}
}</code></pre>
<h5>Event: 'error'<span><a class="mark" href="#stream_event_error" id="stream_event_error">#</a></span></h5>
<div class="api_metadata">
<span>Added in: v0.9.4</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li>
</ul>
<p>The <code>'error'</code> event is emitted if an error occurred while writing or piping
data. The listener callback is passed a single <code>Error</code> argument when called.</p>
<p>The stream is not closed when the <code>'error'</code> event is emitted.</p>
<h5>Event: 'finish'<span><a class="mark" href="#stream_event_finish" id="stream_event_finish">#</a></span></h5>
<div class="api_metadata">
<span>Added in: v0.9.4</span>
</div>
<p>The <code>'finish'</code> event is emitted after the <a href="#stream_writable_end_chunk_encoding_callback"><code>stream.end()</code></a> method
has been called, and all data has been flushed to the underlying system.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> writer = getWritableStreamSomehow();
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i < <span class="hljs-number">100</span>; i++) {
writer.write(<span class="hljs-string">`hello, #<span class="hljs-subst">${i}</span>!\n`</span>);
}
writer.end(<span class="hljs-string">'This is the end\n'</span>);
writer.on(<span class="hljs-string">'finish'</span>, () => {
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'All writes are now complete.'</span>);
});</code></pre>
<h5>Event: 'pipe'<span><a class="mark" href="#stream_event_pipe" id="stream_event_pipe">#</a></span></h5>
<div class="api_metadata">
<span>Added in: v0.9.4</span>
</div>
<ul>
<li><code>src</code> <a href="stream.html#stream_class_stream_readable" class="type"><stream.Readable></a> source stream that is piping to this writable</li>
</ul>
<p>The <code>'pipe'</code> event is emitted when the <a href="#stream_readable_pipe_destination_options"><code>stream.pipe()</code></a> method is called on
a readable stream, adding this writable to its set of destinations.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> writer = getWritableStreamSomehow();
<span class="hljs-keyword">const</span> reader = getReadableStreamSomehow();
writer.on(<span class="hljs-string">'pipe'</span>, (src) => {
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Something is piping into the writer.'</span>);
assert.equal(src, reader);
});
reader.pipe(writer);</code></pre>
<h5>Event: 'unpipe'<span><a class="mark" href="#stream_event_unpipe" id="stream_event_unpipe">#</a></span></h5>
<div class="api_metadata">
<span>Added in: v0.9.4</span>
</div>
<ul>
<li><code>src</code> <a href="stream.html#stream_class_stream_readable" class="type"><stream.Readable></a> The source stream that
<a href="#stream_readable_unpipe_destination">unpiped</a> this writable</li>
</ul>
<p>The <code>'unpipe'</code> event is emitted when the <a href="#stream_readable_unpipe_destination"><code>stream.unpipe()</code></a> method is called
on a <a href="#stream_class_stream_readable"><code>Readable</code></a> stream, removing this <a href="#stream_class_stream_writable"><code>Writable</code></a> from its set of
destinations.</p>
<p>This is also emitted in case this <a href="#stream_class_stream_writable"><code>Writable</code></a> stream emits an error when a
<a href="#stream_class_stream_readable"><code>Readable</code></a> stream pipes into it.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> writer = getWritableStreamSomehow();
<span class="hljs-keyword">const</span> reader = getReadableStreamSomehow();
writer.on(<span class="hljs-string">'unpipe'</span>, (src) => {
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Something has stopped piping into the writer.'</span>);
assert.equal(src, reader);
});
reader.pipe(writer);
reader.unpipe(writer);</code></pre>
<h5>writable.cork()<span><a class="mark" href="#stream_writable_cork" id="stream_writable_cork">#</a></span></h5>
<div class="api_metadata">
<span>Added in: v0.11.2</span>
</div>
<p>The <code>writable.cork()</code> method forces all written data to be buffered in memory.
The buffered data will be flushed when either the <a href="#stream_writable_uncork"><code>stream.uncork()</code></a> or
<a href="#stream_writable_end_chunk_encoding_callback"><code>stream.end()</code></a> methods are called.</p>
<p>The primary intent of <code>writable.cork()</code> is to avoid a situation where writing
many small chunks of data to a stream do not cause a backup in the internal
buffer that would have an adverse impact on performance. In such situations,
implementations that implement the <code>writable._writev()</code> method can perform
buffered writes in a more optimized manner.</p>
<p>See also: <a href="#stream_writable_uncork"><code>writable.uncork()</code></a>.</p>
<h5>writable.destroy([error])<span><a class="mark" href="#stream_writable_destroy_error" id="stream_writable_destroy_error">#</a></span></h5>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
</div>
<ul>
<li><code>error</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this" class="type"><this></a></li>
</ul>
<p>Destroy the stream, and emit the passed <code>'error'</code> and a <code>'close'</code> event.
After this call, the writable stream has ended and subsequent calls
to <code>write()</code> or <code>end()</code> will result in an <code>ERR_STREAM_DESTROYED</code> error.
Implementors should not override this method,
but instead implement <a href="#stream_writable_destroy_err_callback"><code>writable._destroy()</code></a>.</p>
<h5>writable.end([chunk][, encoding][, callback])<span><a class="mark" href="#stream_writable_end_chunk_encoding_callback" id="stream_writable_end_chunk_encoding_callback">#</a></span></h5>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.0.0</td>
<td><p>This method now returns a reference to <code>writable</code>.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>chunk</code> argument can now be a <code>Uint8Array</code> instance.</p></td></tr>
<tr><td>v0.9.4</td>
<td><p><span>Added in: v0.9.4</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>chunk</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="buffer.html#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array" class="type"><Uint8Array></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> Optional data to write. For streams
not operating in object mode, <code>chunk</code> must be a string, <code>Buffer</code> or
<code>Uint8Array</code>. For object mode streams, <code>chunk</code> may be any JavaScript value
other than <code>null</code>.</li>
<li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The encoding if <code>chunk</code> is a string</li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Optional callback for when the stream is finished</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this" class="type"><this></a></li>
</ul>
<p>Calling the <code>writable.end()</code> method signals that no more data will be written
to the <a href="#stream_class_stream_writable"><code>Writable</code></a>. The optional <code>chunk</code> and <code>encoding</code> arguments allow one
final additional chunk of data to be written immediately before closing the
stream. If provided, the optional <code>callback</code> function is attached as a listener
for the <a href="#stream_event_finish"><code>'finish'</code></a> event.</p>
<p>Calling the <a href="#stream_writable_write_chunk_encoding_callback"><code>stream.write()</code></a> method after calling
<a href="#stream_writable_end_chunk_encoding_callback"><code>stream.end()</code></a> will raise an error.</p>
<pre><code class="language-js"><span class="hljs-comment">// write 'hello, ' and then end with 'world!'</span>
<span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'fs'</span>);
<span class="hljs-keyword">const</span> file = fs.createWriteStream(<span class="hljs-string">'example.txt'</span>);
file.write(<span class="hljs-string">'hello, '</span>);
file.end(<span class="hljs-string">'world!'</span>);
<span class="hljs-comment">// writing more now is not allowed!</span></code></pre>
<h5>writable.setDefaultEncoding(encoding)<span><a class="mark" href="#stream_writable_setdefaultencoding_encoding" id="stream_writable_setdefaultencoding_encoding">#</a></span></h5>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v6.1.0</td>
<td><p>This method now returns a reference to <code>writable</code>.</p></td></tr>
<tr><td>v0.11.15</td>
<td><p><span>Added in: v0.11.15</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The new default encoding</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this" class="type"><this></a></li>
</ul>
<p>The <code>writable.setDefaultEncoding()</code> method sets the default <code>encoding</code> for a
<a href="#stream_class_stream_writable"><code>Writable</code></a> stream.</p>
<h5>writable.uncork()<span><a class="mark" href="#stream_writable_uncork" id="stream_writable_uncork">#</a></span></h5>
<div class="api_metadata">
<span>Added in: v0.11.2</span>
</div>
<p>The <code>writable.uncork()</code> method flushes all data buffered since
<a href="#stream_writable_cork"><code>stream.cork()</code></a> was called.</p>
<p>When using <a href="#stream_writable_cork"><code>writable.cork()</code></a> and <code>writable.uncork()</code> to manage the buffering
of writes to a stream, it is recommended that calls to <code>writable.uncork()</code> be
deferred using <code>process.nextTick()</code>. Doing so allows batching of all
<code>writable.write()</code> calls that occur within a given Node.js event loop phase.</p>
<pre><code class="language-js">stream.cork();
stream.write(<span class="hljs-string">'some '</span>);
stream.write(<span class="hljs-string">'data '</span>);
process.nextTick(<span class="hljs-function"><span class="hljs-params">()</span> =></span> stream.uncork());</code></pre>
<p>If the <a href="#stream_writable_cork"><code>writable.cork()</code></a> method is called multiple times on a stream, the
same number of calls to <code>writable.uncork()</code> must be called to flush the buffered
data.</p>
<pre><code class="language-js">stream.cork();
stream.write(<span class="hljs-string">'some '</span>);
stream.cork();
stream.write(<span class="hljs-string">'data '</span>);
process.nextTick(<span class="hljs-function"><span class="hljs-params">()</span> =></span> {
stream.uncork();
<span class="hljs-comment">// The data will not be flushed until uncork() is called a second time.</span>
stream.uncork();
});</code></pre>
<p>See also: <a href="#stream_writable_cork"><code>writable.cork()</code></a>.</p>
<h5>writable.writableHighWaterMark<span><a class="mark" href="#stream_writable_writablehighwatermark" id="stream_writable_writablehighwatermark">#</a></span></h5>
<div class="api_metadata">
<span>Added in: v9.3.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
</ul>
<p>Return the value of <code>highWaterMark</code> passed when constructing this
<code>Writable</code>.</p>
<h5>writable.writableLength<span><a class="mark" href="#stream_writable_writablelength" id="stream_writable_writablelength">#</a></span></h5>
<div class="api_metadata">
<span>Added in: v9.4.0</span>
</div>
<p>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 <code>highWaterMark</code>.</p>
<h5>writable.write(chunk[, encoding][, callback])<span><a class="mark" href="#stream_writable_write_chunk_encoding_callback" id="stream_writable_write_chunk_encoding_callback">#</a></span></h5>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>chunk</code> argument can now be a <code>Uint8Array</code> instance.</p></td></tr>
<tr><td>v6.0.0</td>
<td><p>Passing <code>null</code> as the <code>chunk</code> parameter will always be considered invalid now, even in object mode.</p></td></tr>
<tr><td>v0.9.4</td>
<td><p><span>Added in: v0.9.4</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>chunk</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="buffer.html#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array" class="type"><Uint8Array></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> Optional data to write. For streams
not operating in object mode, <code>chunk</code> must be a string, <code>Buffer</code> or
<code>Uint8Array</code>. For object mode streams, <code>chunk</code> may be any JavaScript value
other than <code>null</code>.</li>
<li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The encoding, if <code>chunk</code> is a string</li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Callback for when this chunk of data is flushed</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> <code>false</code> if the stream wishes for the calling code to
wait for the <code>'drain'</code> event to be emitted before continuing to write
additional data; otherwise <code>true</code>.</li>
</ul>
<p>The <code>writable.write()</code> method writes some data to the stream, and calls the
supplied <code>callback</code> once the data has been fully handled. If an error
occurs, the <code>callback</code> <em>may or may not</em> be called with the error as its
first argument. To reliably detect write errors, add a listener for the
<code>'error'</code> event.</p>
<p>The return value is <code>true</code> if the internal buffer is less than the
<code>highWaterMark</code> configured when the stream was created after admitting <code>chunk</code>.
If <code>false</code> is returned, further attempts to write data to the stream should
stop until the <a href="#stream_event_drain"><code>'drain'</code></a> event is emitted.</p>
<p>While a stream is not draining, calls to <code>write()</code> will buffer <code>chunk</code>, and
return false. Once all currently buffered chunks are drained (accepted for
delivery by the operating system), the <code>'drain'</code> event will be emitted.
It is recommended that once <code>write()</code> returns false, no more chunks be written
until the <code>'drain'</code> event is emitted. While calling <code>write()</code> 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.</p>
<p>Writing data while the stream is not draining is particularly
problematic for a <a href="#stream_class_stream_transform"><code>Transform</code></a>, because the <code>Transform</code> streams are paused
by default until they are piped or a <code>'data'</code> or <code>'readable'</code> event handler
is added.</p>
<p>If the data to be written can be generated or fetched on demand, it is
recommended to encapsulate the logic into a <a href="#stream_class_stream_readable"><code>Readable</code></a> and use
<a href="#stream_readable_pipe_destination_options"><code>stream.pipe()</code></a>. However, if calling <code>write()</code> is preferred, it is
possible to respect backpressure and avoid memory issues using the
<a href="#stream_event_drain"><code>'drain'</code></a> event:</p>
<pre><code class="language-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">write</span>(<span class="hljs-params">data, cb</span>) </span>{
<span class="hljs-keyword">if</span> (!stream.write(data)) {
stream.once(<span class="hljs-string">'drain'</span>, cb);
} <span class="hljs-keyword">else</span> {
process.nextTick(cb);
}
}
<span class="hljs-comment">// Wait for cb to be called before doing any other write.</span>
write(<span class="hljs-string">'hello'</span>, () => {
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Write completed, do more writes now.'</span>);
});</code></pre>
<p>A <code>Writable</code> stream in object mode will always ignore the <code>encoding</code> argument.</p>
<h3>Readable Streams<span><a class="mark" href="#stream_readable_streams" id="stream_readable_streams">#</a></span></h3>
<p>Readable streams are an abstraction for a <em>source</em> from which data is
consumed.</p>
<p>Examples of <code>Readable</code> streams include:</p>
<ul>
<li><a href="http.html#http_class_http_incomingmessage">HTTP responses, on the client</a></li>
<li><a href="http.html#http_class_http_incomingmessage">HTTP requests, on the server</a></li>
<li><a href="fs.html#fs_class_fs_readstream">fs read streams</a></li>
<li><a href="zlib.html">zlib streams</a></li>
<li><a href="crypto.html">crypto streams</a></li>
<li><a href="net.html#net_class_net_socket">TCP sockets</a></li>
<li><a href="child_process.html#child_process_subprocess_stdout">child process stdout and stderr</a></li>
<li><a href="process.html#process_process_stdin"><code>process.stdin</code></a></li>
</ul>
<p>All <a href="#stream_class_stream_readable"><code>Readable</code></a> streams implement the interface defined by the
<code>stream.Readable</code> class.</p>
<h4>Two Reading Modes<span><a class="mark" href="#stream_two_reading_modes" id="stream_two_reading_modes">#</a></span></h4>
<p><code>Readable</code> streams effectively operate in one of two modes: flowing and
paused. These modes are separate from <a href="#stream_object_mode">object mode</a>.
A <a href="#stream_class_stream_readable"><code>Readable</code></a> stream can be in object mode or not, regardless of whether
it is in flowing mode or paused mode.</p>
<ul>
<li>
<p>In flowing mode, data is read from the underlying system automatically
and provided to an application as quickly as possible using events via the
<a href="events.html#events_class_eventemitter"><code>EventEmitter</code></a> interface.</p>
</li>
<li>
<p>In paused mode, the <a href="#stream_readable_read_size"><code>stream.read()</code></a> method must be called
explicitly to read chunks of data from the stream.</p>
</li>
</ul>
<p>All <a href="#stream_class_stream_readable"><code>Readable</code></a> streams begin in paused mode but can be switched to flowing
mode in one of the following ways:</p>
<ul>
<li>Adding a <a href="#stream_event_data"><code>'data'</code></a> event handler.</li>
<li>Calling the <a href="#stream_readable_resume"><code>stream.resume()</code></a> method.</li>
<li>Calling the <a href="#stream_readable_pipe_destination_options"><code>stream.pipe()</code></a> method to send the data to a <a href="#stream_class_stream_writable"><code>Writable</code></a>.</li>
</ul>
<p>The <code>Readable</code> can switch back to paused mode using one of the following:</p>
<ul>
<li>If there are no pipe destinations, by calling the
<a href="#stream_readable_pause"><code>stream.pause()</code></a> method.</li>
<li>If there are pipe destinations, by removing all pipe destinations.
Multiple pipe destinations may be removed by calling the
<a href="#stream_readable_unpipe_destination"><code>stream.unpipe()</code></a> method.</li>
</ul>
<p>The important concept to remember is that a <code>Readable</code> 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 <code>Readable</code> will <em>attempt</em>
to stop generating the data.</p>
<p>For backward compatibility reasons, removing <a href="#stream_event_data"><code>'data'</code></a> event handlers will
<strong>not</strong> automatically pause the stream. Also, if there are piped destinations,
then calling <a href="#stream_readable_pause"><code>stream.pause()</code></a> will not guarantee that the
stream will <em>remain</em> paused once those destinations drain and ask for more data.</p>
<p>If a <a href="#stream_class_stream_readable"><code>Readable</code></a> 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 <code>readable.resume()</code> method is called without a listener
attached to the <code>'data'</code> event, or when a <code>'data'</code> event handler is removed
from the stream.</p>
<p>Adding a <a href="#stream_event_readable"><code>'readable'</code></a> event handler automatically make the stream to
stop flowing, and the data to be consumed via
<a href="#stream_readable_read_size"><code>readable.read()</code></a>. If the <a href="#stream_event_readable"><code>'readable'</code></a> event handler is
removed, then the stream will start flowing again if there is a
<a href="#stream_event_data"><code>'data'</code></a> event handler.</p>
<h4>Three States<span><a class="mark" href="#stream_three_states" id="stream_three_states">#</a></span></h4>
<p>The "two modes" of operation for a <code>Readable</code> stream are a simplified
abstraction for the more complicated internal state management that is happening
within the <code>Readable</code> stream implementation.</p>
<p>Specifically, at any given point in time, every <code>Readable</code> is in one of three
possible states:</p>
<ul>
<li><code>readable.readableFlowing === null</code></li>
<li><code>readable.readableFlowing === false</code></li>
<li><code>readable.readableFlowing === true</code></li>
</ul>
<p>When <code>readable.readableFlowing</code> is <code>null</code>, 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 <code>'data'</code> event, calling the
<code>readable.pipe()</code> method, or calling the <code>readable.resume()</code> method will switch
<code>readable.readableFlowing</code> to <code>true</code>, causing the <code>Readable</code> to begin actively
emitting events as data is generated.</p>
<p>Calling <code>readable.pause()</code>, <code>readable.unpipe()</code>, or receiving backpressure
will cause the <code>readable.readableFlowing</code> to be set as <code>false</code>,
temporarily halting the flowing of events but <em>not</em> halting the generation of
data. While in this state, attaching a listener for the <code>'data'</code> event
will not switch <code>readable.readableFlowing</code> to <code>true</code>.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { PassThrough, Writable } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'stream'</span>);
<span class="hljs-keyword">const</span> pass = <span class="hljs-keyword">new</span> PassThrough();
<span class="hljs-keyword">const</span> writable = <span class="hljs-keyword">new</span> Writable();
pass.pipe(writable);
pass.unpipe(writable);
<span class="hljs-comment">// readableFlowing is now false</span>
pass.on(<span class="hljs-string">'data'</span>, (chunk) => { <span class="hljs-built_in">console</span>.log(chunk.toString()); });
pass.write(<span class="hljs-string">'ok'</span>); <span class="hljs-comment">// will not emit 'data'</span>
pass.resume(); <span class="hljs-comment">// must be called to make stream emit 'data'</span></code></pre>
<p>While <code>readable.readableFlowing</code> is <code>false</code>, data may be accumulating
within the stream's internal buffer.</p>
<h4>Choose One API Style<span><a class="mark" href="#stream_choose_one_api_style" id="stream_choose_one_api_style">#</a></span></h4>
<p>The <code>Readable</code> stream API evolved across multiple Node.js versions and provides
multiple methods of consuming stream data. In general, developers should choose
<em>one</em> of the methods of consuming data and <em>should never</em> use multiple methods
to consume data from a single stream. Specifically, using a combination
of <code>on('data')</code>, <code>on('readable')</code>, <code>pipe()</code>, or async iterators could
lead to unintuitive behavior.</p>
<p>Use of the <code>readable.pipe()</code> method is recommended for most users as it has been
implemented to provide the easiest way of consuming stream data. Developers that
require more fine-grained control over the transfer and generation of data can
use the <a href="events.html#events_class_eventemitter"><code>EventEmitter</code></a> and <code>readable.on('readable')</code>/<code>readable.read()</code>
or the <code>readable.pause()</code>/<code>readable.resume()</code> APIs.</p>
<h4>Class: stream.Readable<span><a class="mark" href="#stream_class_stream_readable" id="stream_class_stream_readable">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v0.9.4</span>
</div>
<h5>Event: 'close'<span><a class="mark" href="#stream_event_close_1" id="stream_event_close_1">#</a></span></h5>
<div class="api_metadata">
<span>Added in: v0.9.4</span>
</div>
<p>The <code>'close'</code> 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.</p>
<p>Not all <a href="#stream_class_stream_readable"><code>Readable</code></a> streams will emit the <code>'close'</code> event.</p>
<h5>Event: 'data'<span><a class="mark" href="#stream_event_data" id="stream_event_data">#</a></span></h5>
<div class="api_metadata">
<span>Added in: v0.9.4</span>
</div>
<ul>
<li><code>chunk</code> <a href="buffer.html#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> The chunk of data. For streams that are not
operating in object mode, the chunk will be either a string or <code>Buffer</code>.
For streams that are in object mode, the chunk can be any JavaScript value
other than <code>null</code>.</li>
</ul>
<p>The <code>'data'</code> 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 <code>readable.pipe()</code>, <code>readable.resume()</code>, or by
attaching a listener callback to the <code>'data'</code> event. The <code>'data'</code> event will
also be emitted whenever the <code>readable.read()</code> method is called and a chunk of
data is available to be returned.</p>
<p>Attaching a <code>'data'</code> 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.</p>
<p>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
<code>readable.setEncoding()</code> method; otherwise the data will be passed as a
<code>Buffer</code>.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> readable = getReadableStreamSomehow();
readable.on(<span class="hljs-string">'data'</span>, (chunk) => {
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Received <span class="hljs-subst">${chunk.length}</span> bytes of data.`</span>);
});</code></pre>
<h5>Event: 'end'<span><a class="mark" href="#stream_event_end" id="stream_event_end">#</a></span></h5>
<div class="api_metadata">
<span>Added in: v0.9.4</span>
</div>
<p>The <code>'end'</code> event is emitted when there is no more data to be consumed from
the stream.</p>
<p>The <code>'end'</code> event <strong>will not be emitted</strong> unless the data is completely
consumed. This can be accomplished by switching the stream into flowing mode,
or by calling <a href="#stream_readable_read_size"><code>stream.read()</code></a> repeatedly until all data has been
consumed.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> readable = getReadableStreamSomehow();
readable.on(<span class="hljs-string">'data'</span>, (chunk) => {
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Received <span class="hljs-subst">${chunk.length}</span> bytes of data.`</span>);
});
readable.on(<span class="hljs-string">'end'</span>, () => {
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'There will be no more data.'</span>);
});</code></pre>
<h5>Event: 'error'<span><a class="mark" href="#stream_event_error_1" id="stream_event_error_1">#</a></span></h5>
<div class="api_metadata">
<span>Added in: v0.9.4</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li>
</ul>
<p>The <code>'error'</code> event may be emitted by a <code>Readable</code> 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.</p>
<p>The listener callback will be passed a single <code>Error</code> object.</p>
<h5>Event: 'readable'<span><a class="mark" href="#stream_event_readable" id="stream_event_readable">#</a></span></h5>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.0.0</td>
<td><p>The <code>'readable'</code> is always emitted in the next tick after <code>.push()</code> is called</p></td></tr>
<tr><td>v10.0.0</td>
<td><p>Using <code>'readable'</code> requires calling <code>.read()</code>.</p></td></tr>
<tr><td>v0.9.4</td>
<td><p><span>Added in: v0.9.4</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>The <code>'readable'</code> event is emitted when there is data available to be read from
the stream. In some cases, attaching a listener for the <code>'readable'</code> event will
cause some amount of data to be read into an internal buffer.</p>
<pre><code class="language-javascript"><span class="hljs-keyword">const</span> readable = getReadableStreamSomehow();
readable.on(<span class="hljs-string">'readable'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
<span class="hljs-comment">// there is some data to read now</span>
<span class="hljs-keyword">let</span> data;
<span class="hljs-keyword">while</span> (data = <span class="hljs-keyword">this</span>.read()) {
<span class="hljs-built_in">console</span>.log(data);
}
});</code></pre>
<p>The <code>'readable'</code> event will also be emitted once the end of the stream data
has been reached but before the <code>'end'</code> event is emitted.</p>
<p>Effectively, the <code>'readable'</code> event indicates that the stream has new
information: either new data is available or the end of the stream has been
reached. In the former case, <a href="#stream_readable_read_size"><code>stream.read()</code></a> will return the
available data. In the latter case, <a href="#stream_readable_read_size"><code>stream.read()</code></a> will return
<code>null</code>. For instance, in the following example, <code>foo.txt</code> is an empty file:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'fs'</span>);
<span class="hljs-keyword">const</span> rr = fs.createReadStream(<span class="hljs-string">'foo.txt'</span>);
rr.on(<span class="hljs-string">'readable'</span>, () => {
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">`readable: <span class="hljs-subst">${rr.read()}</span>`</span>);
});
rr.on(<span class="hljs-string">'end'</span>, () => {
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'end'</span>);
});</code></pre>
<p>The output of running this script is:</p>
<pre><code class="language-txt">$ node test.js
readable: null
end</code></pre>
<p>In general, the <code>readable.pipe()</code> and <code>'data'</code> event mechanisms are easier to
understand than the <code>'readable'</code> event. However, handling <code>'readable'</code> might
result in increased throughput.</p>
<p>If both <code>'readable'</code> and <a href="#stream_event_data"><code>'data'</code></a> are used at the same time, <code>'readable'</code>
takes precedence in controlling the flow, i.e. <code>'data'</code> will be emitted
only when <a href="#stream_readable_read_size"><code>stream.read()</code></a> is called. The
<code>readableFlowing</code> property would become <code>false</code>.
If there are <code>'data'</code> listeners when <code>'readable'</code> is removed, the stream
will start flowing, i.e. <code>'data'</code> events will be emitted without calling
<code>.resume()</code>.</p>
<h5>readable.destroy([error])<span><a class="mark" href="#stream_readable_destroy_error" id="stream_readable_destroy_error">#</a></span></h5>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
</div>
<ul>
<li><code>error</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a> Error which will be passed as payload in <code>'error'</code> event</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this" class="type"><this></a></li>
</ul>
<p>Destroy the stream, and emit <code>'error'</code> and <code>'close'</code>. After this call, the
readable stream will release any internal resources and subsequent calls
to <code>push()</code> will be ignored.
Implementors should not override this method, but instead implement
<a href="#stream_readable_destroy_err_callback"><code>readable._destroy()</code></a>.</p>
<h5>readable.isPaused()<span><a class="mark" href="#stream_readable_ispaused" id="stream_readable_ispaused">#</a></span></h5>
<div class="api_metadata">
<span>Added in: v0.11.14</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li>
</ul>
<p>The <code>readable.isPaused()</code> method returns the current operating state of the
<code>Readable</code>. This is used primarily by the mechanism that underlies the
<code>readable.pipe()</code> method. In most typical cases, there will be no reason to
use this method directly.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> readable = <span class="hljs-keyword">new</span> stream.Readable();
readable.isPaused(); <span class="hljs-comment">// === false</span>
readable.pause();
readable.isPaused(); <span class="hljs-comment">// === true</span>
readable.resume();
readable.isPaused(); <span class="hljs-comment">// === false</span></code></pre>
<h5>readable.pause()<span><a class="mark" href="#stream_readable_pause" id="stream_readable_pause">#</a></span></h5>
<div class="api_metadata">
<span>Added in: v0.9.4</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this" class="type"><this></a></li>
</ul>