0

I'm having trouble understanding, why the following works, that is, why the invocations of the read() function actually return the objects stored in the readable stream.

const { Readable } = require('stream')
var r = new Readable({objectMode: true, read: () => {}}) // dummy read
var a = [1,2,3,4,5,6,7]
r.push(...a)

Now, when I invoke r.read() I get the numbers I pushed into my readable stream r

r.read() // -> 1
r.read() // -> 2
// etc

But I provided a "dummy" read function (read: () => {}) above when creating my readable stream. So, why do I get values back, when calling read?

Help will be much appreciated.

1 Answer 1

1

The answer is simple. You're calling the push method which should be called by your read implementation.

The purpose of push is to say: here's what I've read from the source, but it doesn't have to be called from within the internal methods.

In other words in the process:

  • wait for _read to be called
  • _read something from source
  • push the read chunks to stream
  • return the chunks from read

You simply skipped the two first steps and pushed the data from outside.

Sign up to request clarification or add additional context in comments.

4 Comments

So, am I correct in assuming that the provided read() => {} function is not the one called when invoking r.read(). Or in other words read() => {} is not read([size])?
You are and you're not. It's called alright, but not directly. There's quite a lot machinery in the stream class that calls your _read implementation. Put a console.log in your read function and see for yourself - I suspect _read will get called before your read call.
Thanks. Indeed that helped. The two methods are interlinked in the call stack, but are not identical. That clears my earlier confusion, indeed. I cannot help but wonder, whether the identical naming read of the two functions one that reads data into the stream and the other that reads data from the stream has been a wise choice.
Well - that's why I refer to the internal _read with the underscore - if you were to implement a class derived from Readable then you can simply implement that underscore method. Passing the read function is simply another way of passing this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.