Reading and writing Node.js streams
あまり使わないけどかなり初歩的なところから解説していたわかりやすかった
Readable
code:stream.js
class MyStream extends Readable {
_read() {
// データ流す ReadableStream Event: 'data'
this.push(':>')
// データ完了 ReadableStream Event: 'end'
this.push(null)
}
}
stream.pause
The readable.pause() method will cause a stream in flowing mode to stop emitting 'data' events, switching out of flowing mode. Any data that becomes available will remain in the internal buffer.
code:pause.js
stream.on("data", (chunk) => {
console.log(chunk.toString());
stream.pause(); // Pause receiving data to simulate processing delay
setTimeout(() => {
stream.resume(); // Resume after 1000ms
}, 1000);
});
stream.on("pause", () => console.log("paused."));
stream.on("end", () => console.log("ended."));
例えば resume しないまま pause 状態になると stream も途切れるっぽい(プロセス終了とみなしているだけか?
その場合は Event: end はEmitされない