Following is the code for implementing live streaming by server side chunking in nodeJs, the chunk size mentioned here is of 1MB.
app.js
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.sendFile(__dirname+"/index.html");
});
app.get('/video', (req, res) => {
const range = req.headers.range;
if(!range)
{
res.status(400).send('Require range header');
}
const videoPath = "./HoistingJavaScript.mp4";
const videoSize = fs.statSync(videoPath).size;
// console.log(videoSize);
const chunkSize = 10**6; //10^6, O/p: 1000000
const start = Number(range.replace(/\D/g, "")); // \D to replace all non-digit characters with an empty string
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);//partial data 206
const videoStream = fs.createReadStream(videoPath, {
start, end
});
videoStream.pipe(res);
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Video Chunking Streaming</title>
</head>
<body>
<h1>Header</h1>
<video id="vidPlr" width="50%" controls>
<source src="/video" type="video/mp4">
</video>
</body>
</html>
Top comments (0)