If you are going to build streaming web application with multiple concurrent connections. you’ll definitely benefit from Node capabilities. And it comes to play video in the web application then Node.js suits best because it provides the data in chunks and plays a video of big size in much efficient way.
Steams for playing Video
Mainly with Streams, data is send to client in chunks at at time instead of sending everything to the client at single time.
With this approach, client does not download the complete video at once, But it downloads the few seconds video at first and then download the next few seconds video while the previously downloaded video plays.
Folder Structure
In the above folder structure we have server.js file for performing all server side related stuff, index.html file for setting the html5 video tag with source route and assets folder for video file.
1. server.js
const express = require('express')
const fs = require('fs')
const path = require('path')
const app = express()
app.get('/', function(req, res) {
res.sendFile(path.join(__dirname + '/index.html'))
})
app.get('/video', function(req, res) {
const path = 'assets/sample.mp4'
const stat = fs.statSync(path)
const fileSize = stat.size
const range = req.headers.range
if (range) {
const parts = range.replace(/bytes=/, "").split("-")
const start = parseInt(parts[0], 10)
const end = parts[1]
? parseInt(parts[1], 10)
: fileSize-1
const chunksize = (end-start)+1
const file = fs.createReadStream(path, {start, end})
const head = {
'Content-Range': `bytes ${start}-${end}/${fileSize}`,
'Accept-Ranges': 'bytes',
'Content-Length': chunksize,
'Content-Type': 'video/mp4',
}
res.writeHead(206, head)
file.pipe(res)
} else {
const head = {
'Content-Length': fileSize,
'Content-Type': 'video/mp4',
}
res.writeHead(200, head)
fs.createReadStream(path).pipe(res)
}
})
app.listen(3000, function () {
console.log('App is running on port 3000')
})
In the above file:
At the top we have included needed NPM packages. After that we have a get method served on route ‘/’ for serving the html file. Then there is a get method with route ‘/video’ which is being called from html file. In this method at first the filesize is detected with statSync method of fs. after that with stream video is downloaded to client in chunks. With every new request from client the value of start and end is changing to get the next chunk of video. 206 is set in response header to send only newly made stream(chunk of video).
2. index.html
<div class="row">
<div class="col-md-3 col-md-offset-3">
<video style="height: 400px; width:600px;" id="videoPlayer" controls muted="muted" autoplay>
<source src="http://localhost:3000/video" type="video/mp4">
</video>
</div>
</div>
In the above file we have set the HTML5 video tag with source route.
Video streaming with Node.js is very easy and one of the very efficient solutions for the video streaming application. If you are new to Node.js then click here find many demos to start the app for enterprise-level application
Let me know your thoughts over the email demo.jsonworld@gmail.com. I would love to hear them and If you like this article, share with your friends.
Further reading:
☞ The Differences Between a Junior, Mid-Level and Senior Developer
☞ Angular 8 Routing & Navigation Tutorial with Example
☞ Building Real-World Microservices with Node.js
☞ Golang vs Node.js: What’s the Difference?
☞ Build a Chatbot from Scratch - Dialogflow on Node.js
#node-js #javascript