How To Stream A Video With NodeJS
Tags: webdev, javascript, programming
Published: 2023-01-13 20:23:45

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

![Introduction gif](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0qyu8m3d1hro6ht8zyg9.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 
```Javascript
const express = require("express");
const app = express();
const fs = require("fs");
```
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
____
```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>
```
Now we'll route the html page and listen to our Port
```Javascript
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!");
});
```
Now You Should have this
![First result](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ogkqet8oagd7d1tpm9nt.png)

To the main part of this Project😉😉😉
You'll create a route '/video' and set the request object headers It'll look like this:
```javascript
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);
});
```
Now we'll set our videoPath, videoSize and headers
The route now looks like this;
```javascript
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);
});
```


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 
```javascript
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!");
});
```
Here Is the Link To the Code base
[Github Link](https://github.com/FredAbod/Video-Streaming-With-Nodejs)