Video streaming in Nodejs

--

Photo by Mika Baumeister on Unsplash

What are the streams in Nodejs?

Just like arrays or strings, streams are the objects which are basically the collection of data. Streams don't have the fixed size in the memory means for a large amount of data, the data get loaded up in small chunks instead of loading it at once. This provides the major advantages of it which are:

  • Memory efficiency: you don’t need to load large amounts of data in memory before you are able to process it
  • Time efficiency: it takes way less time to start processing data since you can start processing as soon as you have it, rather than waiting till the whole data payload is available

for e.g. When we see the videos on youtube, whole video content doesn’t get loaded up fully at first, it loaded up with small chunks and video starts playing without wasting a lot of time on getting full data at once.

Now we will dive into the video streaming example.

Firstly we have downloaded the video from the web and stored into the project folder of the name Funny-Status-Video.mp4.

Now in HTML file, we have added the video tag, where src and the type are mentioned.

Now in js file firstly we have rendered the HTML file whenever we have root route which is ‘/’. The second path we have is ‘/getVideo’ whenever this route got hit, it will get hit when video starts playing.

The two basic things we need to calculate and send in the headers are content-length and content-range. Content-range tells us the range from where to where we are showing the video and content-length tells us the total length of the chunk we are sending now we sending 1 MB.

After setting the headers we set the response type status code which is 206 which means this is partial content.

In the end, we created video read stream for this particular chunk by the method fs.createReadStream(videoPath, { start, end }) and we have streamed the video chunk to the client by the command videoStream.pipe().

The output is shown below without the video getting delayed:

Well, that’s all, I hope I have provided a basic understanding of streaming. This is how video is streamed in nodejs without getting stuck

❤️ Like, Share or Leave A Comment!

If you enjoyed this post, don’t forget to give it a 👏🏼, share it with a friend you think might benefit from it and leave a comment! Stay tuned for more exciting blogs on Flutter, Elixir, React, Angular, Ruby, etc.

Thanks !!

--

--