My readable stream won't pause when I say so. What am I missing here?
I would expect the output to pause every second for the duration of a second, but it doesn't.
const { Readable, Writable } = require('stream');
const r = new Readable({
read() {
this.push(Math.random().toString());
}
});
const w = new Writable({
write(data, enc, next) {
console.log(data.toString());
setTimeout(next, 10)
}
});
r.pipe(w);
setInterval(() => {
if(r.isPaused()) {
console.log('>>>>>>>>>>> RESUMING')
r.resume();
} else {
console.log('>>>>>>>>>>> PAUSING')
r.pause();
}
}, 1000);
By using pipe/unpipe I was able to mimic the paus/resume behaviour.
const { Readable, Writable } = require('stream');
const r = new Readable({
highWaterMark: 1,
read() {
const randomNumber = Math.random();
this.push(randomNumber.toString());
}
});
const w = new Writable({
highWaterMark: 1,
write(randomNumber, enc, next) {
console.log(randomNumber.toString())
setTimeout(next, 1000)
}
});
let isPiped = true;
r.pipe(w);
setInterval(() => {
if(isPiped) {
console.log('>>>>>>>>>>>>>>>>>>>>>>>>>>>>> PAUSE')
r.unpipe(w);
isPiped = false
} else {
console.log('>>>>>>>>>>>>>>>>>>>>>>>>>>>>> RESUME')
r.pipe(w);
isPiped = true;
}
}, 10000);