@@ -1108,17 +1108,48 @@ automatically until the internal buffer is fully drained.
1108
1108
1109
1109
``` js
1110
1110
const readable = getReadableStreamSomehow ();
1111
+
1112
+ // 'readable' may be triggered multiple times as data is buffered in
1111
1113
readable .on (' readable' , () => {
1112
1114
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
1113
1117
while (null !== (chunk = readable .read ())) {
1114
- console .log (` Received ${ chunk .length } bytes of data.` );
1118
+ console .log (` Read ${ chunk .length } bytes of data.. .` );
1115
1119
}
1116
1120
});
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
+ });
1117
1126
```
1118
1127
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
+ ```
1122
1153
1123
1154
A ` Readable ` stream in object mode will always return a single item from
1124
1155
a call to [ ` readable.read(size) ` ] [ stream-read ] , regardless of the value of the
0 commit comments