@@ -1127,17 +1127,48 @@ automatically until the internal buffer is fully drained.
11271127
11281128``` js 
11291129const  readable  =  getReadableStreamSomehow ();
1130+ 
1131+ //  'readable' may be triggered multiple times as data is buffered in
11301132readable .on (' readable'  , () =>  {
11311133  let  chunk;
1134+   console .log (' Stream is readable (new data received in buffer)'  );
1135+   //  Use a loop to make sure we read all currently available data
11321136  while  (null  !==  (chunk =  readable .read ())) {
1133-     console .log (` Received  ${ chunk .length }   bytes of data.`  );
1137+     console .log (` Read  ${ chunk .length }   bytes of data.. .`  );
11341138  }
11351139});
1140+ 
1141+ //  'end' will be triggered once when there is no more data available
1142+ readable .on (' end'  , () =>  {
1143+   console .log (' Reached end of stream.'  );
1144+ });
11361145``` 
11371146
1138- The ` while `  loop is necessary when processing data with
1139- ` readable.read() ` . Only after ` readable.read() `  returns ` null ` ,
1140- [ ` 'readable' ` ] [ ]  will be emitted.
1147+ Each call to ` readable.read() `  returns a chunk of data, or ` null ` . The chunks
1148+ are not concatenated. A ` while `  loop is necessary to consume all data
1149+ currently in the buffer. When reading a large file ` .read() `  may return ` null ` ,
1150+ having consumed all buffered content so far, but there is still more data to
1151+ come not yet buffered. In this case a new ` 'readable' `  event will be emitted
1152+ when there is more data in the buffer. Finally the ` 'end' `  event will be
1153+ emitted when there is no more data to come.
1154+ 
1155+ Therefore to read a file's whole contents from a ` readable ` , it is necessary
1156+ to collect chunks across multiple ` 'readable' `  events:
1157+ 
1158+ ``` js 
1159+ const  chunks  =  [];
1160+ 
1161+ readable .on (' readable'  , () =>  {
1162+   let  chunk;
1163+   while  (null  !==  (chunk =  readable .read ())) {
1164+     chunks .push (chunk);
1165+   }
1166+ });
1167+ 
1168+ readable .on (' end'  , () =>  {
1169+   const  content  =  chunks .join (' '  );
1170+ });
1171+ ``` 
11411172
11421173A ` Readable `  stream in object mode will always return a single item from
11431174a call to [ ` readable.read(size) ` ] [ stream-read ] , regardless of the value of the
0 commit comments