[node.js] stream - three states (5)
https://nodejs.org/api/stream.html#three-states 을 참고한 글입니다.
'flowing, paused mode' 이 두가지 운영방식은 Readable stream 구현체 안에서 발생하는 다양한 내부 상태를 간소화하여 추상화된 것이다. 모든 Readable 은 3가지 중 하나의 상태를 갖게 된다.
- readable.readableFlowing == null
- readable.readableFlowing == false
- readable.readableFlowing == true
제공받은 데이터를 소비할 로직이 없을 경우 null 상태를 갖는다. 그러므로 스트림은 데이터를 생성하지 않을 것입니다. readable.pipe(), redable.resume() 중 하나를 실행해야 'readable.readableFlowing == true' 으로 변환될것입니다. true로 되면 생성된 데이터를 방출하게 됩니다.
readable.pused(), readable.unpip() 중 하나를 호출하거나 backpressure를 받으면 'readable.readableFlowing == false' 으로 상태가 변경됩니다. 일시적으로 데이터 흐름이 중단됩니다. 그렇다고 데이터 생성이 중단되진 않습니다. false인 상태에서 'data' 콜백을 추가해도 true로 변환되지 않습니다. resume() 또는 pipe()를 호출해야만 true로 변환됩니다.
(backpressure는 consumer 쪽에서 데이터를 처리하는 속도보다 받는 속도가 더 빠를 때 데이터가 넘치는걸 방지해주는 로직입니다.)
code for readable.readableFlowing == null
const fs = require('fs')
const rs = fs.createReadStream('lowercase.txt');
console.log(rs.readableFlowing) // nulll
code for readable.readableFlowing == true
const fs = require('fs')
const rs = fs.createReadStream('lowercase.txt');
rs.on('data', (chunk) => {
console.log(chunk)
});
console.log(rs.readableFlowing) // true
code for switching null to true
const fs = require('fs')
const rs = fs.createReadStream('lowercase.txt');
console.log(rs.readableFlowing) // null
rs.resume()
console.log(rs.readableFlowing) // true
rs.on('data',(c) => {
console.log(c)
})
code for switching false to true
const { PassThrough, Writable } = require('node:stream');
const pass = new PassThrough();
const writable = new Writable();
pass.pipe(writable);
pass.unpipe(writable);
console.log(pass.readableFlowing) // readableFlowing is now false.
pass.on('data', (chunk) => { console.log(chunk.toString()); });
console.log(pass.readableFlowing) // readableFlowing is still false.
pass.write('ok'); // Will not emit 'data'.
pass.resume(); // Must be called to make stream emit 'data'.
console.log(pass.readableFlowing) // readableFlowing is now true.