@@ -1108,17 +1108,48 @@ automatically until the internal buffer is fully drained.
11081108
11091109``` js
11101110const readable = getReadableStreamSomehow ();
1111+
1112+ // 'readable' may be triggered multiple times as data is buffered in
11111113readable .on (' readable' , () => {
11121114 let chunk;
1115+ console .log (' Stream is readable (new data received in buffer)' );
1116+ // Use a loop to make sure we read all currently available data
11131117 while (null !== (chunk = readable .read ())) {
1114- console .log (` Received ${ chunk .length } bytes of data.` );
1118+ console .log (` Read ${ chunk .length } bytes of data.. .` );
11151119 }
11161120});
1121+
1122+ // 'end' will be triggered once when there is no more data available
1123+ readable .on (' end' , () => {
1124+ console .log (' Reached end of stream.' );
1125+ });
11171126```
11181127
1119- The ` while ` loop is necessary when processing data with
1120- ` readable.read() ` . Only after ` readable.read() ` returns ` null ` ,
1121- [ ` 'readable' ` ] [ ] will be emitted.
1128+ Each call to ` readable.read() ` returns a chunk of data, or ` null ` . The chunks
1129+ are not concatenated. A ` while ` loop is necessary to consume all data
1130+ currently in the buffer. When reading a large file ` .read() ` may return ` null ` ,
1131+ having consumed all buffered content so far, but there is still more data to
1132+ come not yet buffered. In this case a new ` 'readable' ` event will be emitted
1133+ when there is more data in the buffer. Finally the ` 'end' ` event will be
1134+ emitted when there is no more data to come.
1135+
1136+ Therefore to read a file's whole contents from a ` readable ` , it is necessary
1137+ to collect chunks across multiple ` 'readable' ` events:
1138+
1139+ ``` js
1140+ const chunks = [];
1141+
1142+ readable .on (' readable' , () => {
1143+ let chunk;
1144+ while (null !== (chunk = readable .read ())) {
1145+ chunks .push (chunk);
1146+ }
1147+ });
1148+
1149+ readable .on (' end' , () => {
1150+ const content = chunks .join (' ' );
1151+ });
1152+ ```
11221153
11231154A ` Readable ` stream in object mode will always return a single item from
11241155a call to [ ` readable.read(size) ` ] [ stream-read ] , regardless of the value of the
0 commit comments