0

I am building a server that serves a video to a user. The server works as expected, but when I try to switch to a different video (going to different URL), the previous video continues to play (i have more explanation). I can't use HTML because user needs to dowload the whole video before playing.

Here is my server code:

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

let app = express();
var server = require("http").createServer(app);
server.listen(3000, () =>
    console.log("Server started on port 3000, and listening for requests")
);
app.use(express.static('public'));

var videoPath = "F:/Videos/harh.mkv"
var videoSize = fs.statSync(videoPath).size;

var videoSize
var videoPath, start, end;
app.get('*', function(req, res){
    var url = req.originalUrl;
    url = decodeURIComponent(url)
    if(!(url === "/api/video")){
        console.log("Accessed from " + url);
        videoPath = `F:/Videos${url}`;
        console.log(videoPath + " <--- this is the video path");
        res.sendFile(__dirname + '/public/index.html'); 
        start=0; end=0;
    }else{    
        videoSize = fs.statSync(videoPath).size;
        var range = req.headers.range;
        if(!range) res.status(400).send("Requires a valid range")
        var CHUNK_SIZE = 10 ** 6
        start = Number(range.replace(/\D/g, ""))
        end  = Math.min(start + CHUNK_SIZE, videoSize-1);
        var contentLength = end - start + 1
        var headers = {
            "Content-Range": `bytes ${start}-${end}/${videoSize}`,
            "Accept-Ranges" : "bytes",
            "Content-Lenght": contentLength,
            "Content-Type": "multipart/byteranges; boundary=MY_BOUNDARY",
        }
        res.writeHead(206, headers)
        var videoStream = fs.createReadStream(videoPath, {start, end});
        videoStream.pipe(res);
    }
});

and here is my Html:

<body>
    <video src="/api/video" controls class="video">

    </video>
</body> 

What is the Main problem: This works as expected But if i change the video ( going to another url) the previous video plays.

Example: http://localhost:3000/test.mkv (10 sec vid) loads this page. if we go to http://localhost:3000/nyancat.mkv (30sec vid) first few second the previous video plays (test.mkv) but after some time nyancat.mkv starts to play.

Each URL needs to play different video.

Dfr
  • 31
  • 8

0 Answers0