Menu Close

How To Stream A Video With NodeJS

How To Stream A Video With NodeJS



In this article I would be showing you how I used Nodejs to stream a video. Lets Dive right into it:

Introduction gif

All you need to carry out this task Is EXPRESS and NODEMON to (restart your server).

To begin Do:

npm init-y


npm i express nodemon -D


Now we’ll create our Root directory
touch index.js
OR create a javascript file called index.js


Now we’ll Import our Dependencies

const express = require("express");
const app = express();
const fs = require("fs");
Enter fullscreen mode

Exit fullscreen mode

Now we’ll create a Simple HTML page to stream the video


But first we need to create an html file so

touch index.html


<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Video Streaming With Node</title>
        <style>
            body {
                margin: 5% auto;
                max-width: 100%;
                background-color: rgb(14, 14, 14);
                padding-top: 10%;
                padding-left: 35%;
            }
        </style>
    </head>
    <body>
        <video id="videoPlayer" width="50%" controls muted="muted" autoplay>
            <source src="/video" type="video/mp4" />
        </video>
    </body>
</html>
Enter fullscreen mode

Exit fullscreen mode

Now we’ll route the html page and listen to our Port

const express = require("express");
const app = express();
const fs = require("fs");
app.get("/", function (req, res) {
    res.sendFile(__dirname + "/index.html");
});
app.listen(8000, function () {
    console.log("Listening on port 8000!");
});
Enter fullscreen mode

Exit fullscreen mode

Now You Should have this
First result

To the main part of this Project😉😉😉
You’ll create a route ‘/video’ and set the request object headers It’ll look like this:

app.get("/video", function (req, res) {
    const range = req.headers.range;
    if (!range) {
        res.status(400).send("Requires Range header");
    }
 res.writeHead(206, headers);
    const videoStream = fs.createReadStream(videoPath, { start, end });
    videoStream.pipe(res);
});
Enter fullscreen mode

Exit fullscreen mode

Now we’ll set our videoPath, videoSize and headers
The route now looks like this;

app.get("/video", function (req, res) {
    const range = req.headers.range;
    if (!range) {
        res.status(400).send("Requires Range header");
    }
    const videoPath = "file_example_MP4_480_1_5MG.mp4";
    const videoSize = fs.statSync("file_example_MP4_480_1_5MG.mp4").size;
    const CHUNK_SIZE = 10 ** 6;
    const start = Number(range.replace(/\D/g, ""));
    const end = Math.min(start + CHUNK_SIZE, 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 videoStream = fs.createReadStream(videoPath, { start, end });
    videoStream.pipe(res);
});
Enter fullscreen mode

Exit fullscreen mode

And that’s basically IT. All you need is your video in the same folder directory as your project and re-editing the name of the video in the code.
Your Working directory should be like this

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

app.get("/", function (req, res) {
    res.sendFile(__dirname + "/index.html");
});

app.get("/video", function (req, res) {
    const range = req.headers.range;
    if (!range) {
        res.status(400).send("Requires Range header");
    }
    const videoPath = "file_example_MP4_480_1_5MG.mp4";
    const videoSize = fs.statSync("file_example_MP4_480_1_5MG.mp4").size;
    const CHUNK_SIZE = 10 ** 6;
    const start = Number(range.replace(/\D/g, ""));
    const end = Math.min(start + CHUNK_SIZE, 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 videoStream = fs.createReadStream(videoPath, { start, end });
    videoStream.pipe(res);
});

app.listen(8000, function () {
    console.log("Listening on port 8000!");
});
Enter fullscreen mode

Exit fullscreen mode

Here Is the Link To the Code base
Github Link

View Source
Posted in NodeJs