Pipe stream with Nodejs

Jevgeni Glazunov
2 min readApr 13, 2021

--

I’ve been a struggle for some time with the piping a stream. But after some research in docs, I came out with I guess a pretty nice solution. I’m not an expert, I learn something new and just want to share my achievement.

So I had a problem. I should pipe a stream from the remote server through my node app and read it on the client-side. Client → request → Node → request → remote server → response stream → Node → pipe stream → Client read stream.

It’s come out that the Node part was very easy.

Node side stream pipe

Basically, you use a method pipe() on the body — which should be a stream, (if not you will get an error) to a response that you will send to a client.

The Client-side was very tricky for me. Actually, MDN had the solution in their docs. But I found this solution too long in code and they been using a promise-based solution, and I decide to use async-await instead.

As you can see when btn is clicked I send a request to my Node app and I use the .getReader() method on the body that I’ve got from with response to get a reader object. If we use the read() method on the reader object we can extract done and value properties.

— Done is a boolean it indicates if a stream is closed (true) or not (false). If done is true log a message that the stream is over.

Value is our data encoded as uint8array which we decode to get a string.

In the end, we use a callback that will run this function until the done property gets value true.

I hope that this was helpful. If there is a better solution, please share it!

--

--

Jevgeni Glazunov
Jevgeni Glazunov

No responses yet