Video Streaming with Node.js

Video Streaming with Node.js

Video Streaming with Node.js.Video streaming with Node.js is very easy and one of the very efficient solutions for the video streaming application.

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.

Let's Get Started

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.

Conclusion

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 [email protected]. 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

Microservices in Node.js

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

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

How to Hire Node.js Developers And How Much Does It Cost?

A Guide to Hire Node.js Developers who can help you create fast and efficient web applications. Also, know how much does it cost to hire Node.js Developers.

Top 7 Most Popular Node.js Frameworks You Should Know

Node.js is an open-source, cross-platform, runtime environment that allows developers to run JavaScript outside of a browser. In this post, you'll see top 7 of the most popular Node frameworks at this point in time (ranked from high to low by GitHub stars).

Hire Node.JS Developers | Skenix Infotech

We are providing robust Node.JS Development Services with expert Node.js Developers. Get affordable Node.JS Web Development services from Skenix Infotech.

Node.js for Beginners - Learn Node.js from Scratch (Step by Step)

Node.js for Beginners - Learn Node.js from Scratch (Step by Step) - Learn the basics of Node.js. This Node.js tutorial will guide you step by step so that you will learn basics and theory of every part. Learn to use Node.js like a professional. You’ll learn: Basic Of Node, Modules, NPM In Node, Event, Email, Uploading File, Advance Of Node.

Hands on with Node.Js Streams | Examples & Approach

The practical implications of having Streams in Node.js are vast. Nodejs Streams are a great way to handle data chunks and uncomplicate development.