How to stream large .mp4 files?
Streaming large video files from the server to the client which might be a web app or mobile apps inefficient manner!
We can’t send the entire video once to a client. because there are conditions like the bandwidth and data restrictions of the user.
Let’s say youtube, the user may watch some part of the video and went away for some reason, if he opened that video again, it should not load the entire video from start.
Here is the part we need some mechanism to handle this situation.
Nodejs stream API comes into the picture, its more efficient than reading a file in a conventional manner and waiting for the callbacks to resolve.
Created a basic video streaming server to explain it little better.
The flow of the system:
- User visits the site (index.html)
- The html5 video component in index.html is pointed to URL of the video that is streaming by server
- The video request is handler by the server by processing range header and sends out part of the video as partial content
Setting up project:
- Open terminal
- mkdir <project name>
- cd <project name>
- npm init -y
- Open your favourite text editor
- Create index.html on that folder (check below html code, use it there)
- Create a server.js file(check the js code provided below)
- Run the command “node server.js”
- Open browser and navigate to “localhost:3000”
Complete source code:
We will need a index.html file show the video that coming from the server!
Finally we can see the result in the browser