I was interested by streams how they work in the node.js. So I read about them in the official documentation and did some tests. After the one test I was wondering by his result.
And here it is:
import { Readable } from 'stream';
class ReadableOwn extends Readable {
data = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];
_read(hwm) {
let pData = this.data.shift();
if (pData) {
console.log(hwm, pData, this.push(pData));
} else this.push(null);
}
}
let myreadable = new ReadableOwn({ highWaterMark: 4, encoding: 'utf8' });
If I use this event:
myreadable.on("readable", () => {
let chunk = myreadable.read();
console.log(chunk);
})
I am getting the next result:
4 a true
4 b true
ab
4 c true
4 d true
4 e true
4 f false
4 g false
cdefg
4 h true
4 i true
4 j true
4 k false
4 l false
hijkl
4 m true
4 n true
4 o true
4 p false
4 q false
mnopq
4 r true
4 s true
4 t true
4 u false
4 v false
rstuv
4 w true
4 x true
4 y true
4 z false
wxyz
null
What is going on with start? I pointed HighWaterMark 4 so why I got 2 characters? By the way this.push(pData) after "ab" still returns true that means that inner buffer not overflowed. Why then did I get "ab" instead of "abcd"?
Once the total size of the internal read buffer reaches the threshold specified by highWaterMark, 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 readable._read() method that is used to fill the read buffer).
What case is mentioned in the documentation?
P.S Sorry for two questions together but they interconnected in understanding.