I am trying to understand node flows and their life cycle. So, I want to split the contents of the stream into n-parts. The following code explains my intentions and shows that I have already tried something myself. I omitted some details
I have a stream that just generates some data (just a sequence of numbers):
class Stream extends Readable { constructor() { super({objectMode: true, highWaterMark: 1}) this.counter = 0 } _read(size) { if(this.counter === 30) { this.push(null) } else { this.push(this.counter) } this.counter += 1 } } const stream = new Stream() stream.pause();
function that tries to take n of the following fragments:
function take(stream, count) { const result = [] return new Promise(function(resolve) { stream.once('readable', function() { var chunk; do { chunk = stream.read() if (_.isNull(chunk) || result.length > count) { stream.pause() break } result.push(chunk) } while(true) resolve(result) }) }) }
and want to use it as follows:
take(stream, 3) .then(res => { assert.deepEqual(res, [1, 2, 3]) return take(stream, 3) }) .then(res => { assert.deepEqual(res, [4, 5, 6]) })
What is an idiomatic way to do this?
kharandziuk
source share