#Make Readable.read() return Buffer

14 messages · Page 1 of 1 (latest)

round mist
#

How can I make Readable.read() return Buffer() instead of Any? Is there a generic for this?

obsidian umbra
#

You can specify the type of data returned by a Node.js Readable stream by using generics.
When you create a Readable stream, use Readable<Buffer> to indicate it should work with buffers.
For example: const stream = new Readable<Buffer>({...}).
Now, when you call stream.read(), TypeScript will infer the return type as Buffer instead of any.
This approach ensures type safety and better IntelliSense in your code.

round mist
#

I can’t use Readable<Buffer>

#

I am on Deno with @types/node though

#

My Readable from node:stream isn’t a generic

torn valve
#

@round mist You can't change the runtime behavior via generics anyway

#

It looks like the output of read depends mutable internal stuff so it's not really possible for the method to automatically return the 'right' type.

#

I'm not sure why it returns any - if I'm reading this right, it seems like string | Buffer | null would be correct...

(method) Stream.Readable.read(size?: number): any
The readable.read() method reads data out of the internal buffer and returns it. If no data is available to be read, null is returned. By default, the data is returned as a Buffer object unless an encoding has been specified using the readable.setEncoding() method or the stream is operating in object mode.

#

... but maybe it can return other things?

#

But either way, you're either going to have to check that it's a buffer or just use a type assertion to assert that it's a buffer.

round mist
#

Yeah this seems dumb

#

Is there a better way for me to turn a udp buffer into a stream so I can parse it?

torn valve
#

Don't really know; not an area of node APIs that I'm familiar with, but having to do a type-check or assertion on an API that may return multiple types doesn't seem unreasonable to me.

#

If you're doing this a lot you can always wrap it in a method.