Open In App

How to build Video Streaming Application using Node.js ?

Last Updated : 19 Jul, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we are going to create a Video Streaming Application. A video streaming application is used to stream or play video, like a simple video player.

Functionality: Play video

Approach: We are going to use express for this project, and create a server file app.js then we will create an HTML file index.html containing a video link that point to the videoplayer route of the server file(app.js.). Inside the server file, we will send the index.html to the home page, then we will use different types of build-in modules for the complete setup of the video player route inside the server file.

Implementation: Below is the step-by-step implementation of the above approach.

Step 1: Project Setup

Initializes NPM: Create and Locate your project folder into the terminal & type the command

npm init -y

It initializes our node application & makes a package.json file.

Install Dependencies: Locate your root project directory into the terminal and type the command

npm install express 

To install Express as dependencies inside your project

Create Server File: Create an ‘app.js’ file, inside this file require the Express Module and File System Module, and create a constant ‘app’ for creating an instance of the express module.

const express = require('express');
const fs = require('fs');
const app = express();

Step 2: Setup Home Page 

Create Index.html file: Let’s create a simple HTML file consists a single line inside the body tag which is basically used to set the video path and width of the video. We will set the video path to the ‘videoplayer’ and later in step 3, we will set up this ‘videoplayer’ request inside our server file(app.js) to stream the video.
index.html

HTML




<!DOCTYPE html>
<html lang="en">
<head>
    <title>Video Player</title>
</head>
<body>
    <video src="/videoplayer" width="1080px" 
           controls></video>
</body>
</html>


Send the file to the home page: Now create a get request for the home page which just send this index.html to the browser.

app.get('/', (req, res) => {
   res.sendFile(__dirname + '/index.html');
})

Step 3: Setup videoplayer route: Now create a get request for the videoplayer.

app.get('/videoplayer', (req, res) => {

})

Inside this route follow the below steps.

Create a const range: This contains the range value that we get from the header.

const range = req.headers.range

Set Video Path: Here we have to create a const videoPath and set it to the location of the video.

const videoPath = pathOfVideo

replace pathOfVideo with the location of your video file.

Set Video Size: Now we have to use the fs module statSync method and pass the video path then calculate the size.

const videoSize  = fs.statSync(videoPath).size

Set Chunk Size: Use just need to use the below code to set chunk size for streaming in Node.js.

const chunkSize = 1 * 1e6;

Create const start and end: They are used to calculate the starting and end position of the video

const start = Number(range.replace(/\D/g, ""))
const end = Math.min(start + chunkSize, videoSize - 1)

Calculate the content length and set it to a variable:

const contentLength = end - start + 1;

Set header for playing video:

const headers = {
    "Content-Range" : `bytes ${start}-${end}/${videoSize}`,
    "Accept-Ranges" : "bytes",
    "Content-Length" : contentLength,
    "Content-Type" : "video/mp4"
}

res.writeHead(206, headers)

Create Video Stream and Pipe it with the response: 

const stream = fs.createReadStream(videoPath, {start, end})

stream.pipe(res)

Complete Code: Below is the complete code to build Note Taking Application using Node.js:

app.js




const express = require('express');
const fs = require('fs');
const app = express();
  
app.get('/', (req, res) => {
    res.sendFile(__dirname + '/index.html');
})
  
app.get('/videoplayer', (req, res) => {
    const range = req.headers.range
    const videoPath = './video.mp4';
    const videoSize = fs.statSync(videoPath).size
    const chunkSize = 1 * 1e6;
    const start = Number(range.replace(/\D/g, ""))
    const end = Math.min(start + chunkSize, videoSize - 1)
    const contentLength = end - start + 1;
    const headers = {
        "Content-Range": `bytes ${start}-${end}/${videoSize}`,
        "Accept-Ranges": "bytes",
        "Content-Length": contentLength,
        "Content-Type": "video/mp4"
    }
    res.writeHead(206, headers)
    const stream = fs.createReadStream(videoPath, {
        start,
        end
    })
    stream.pipe(res)
})
app.listen(3000);


index.html




<!DOCTYPE html>
<html lang="en">
<head>
    <title>Video Player</title>
</head>
<body>
    <video src="/videoplayer" width="1080px" 
           controls></video>
</body>
</html>


Output:

 



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads