@@ -1127,17 +1127,48 @@ automatically until the internal buffer is fully drained.
1127
1127
1128
1128
``` js
1129
1129
const readable = getReadableStreamSomehow ();
1130
+
1131
+ // 'readable' may be triggered multiple times as data is buffered in
1130
1132
readable .on (' readable' , () => {
1131
1133
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
1132
1136
while (null !== (chunk = readable .read ())) {
1133
- console .log (` Received ${ chunk .length } bytes of data.` );
1137
+ console .log (` Read ${ chunk .length } bytes of data.. .` );
1134
1138
}
1135
1139
});
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
+ });
1136
1145
```
1137
1146
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
+ ```
1141
1172
1142
1173
A ` Readable ` stream in object mode will always return a single item from
1143
1174
a call to [ ` readable.read(size) ` ] [ stream-read ] , regardless of the value of the
0 commit comments