-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
48 lines (39 loc) · 1.33 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
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) {
// Ensure there is a range given for the video
const range = req.headers.range;
if (!range) {
res.status(400).send("Requires Range header");
}
// get video stats (about 61MB)
const videoPath = "bigbuck.mp4";
const videoSize = fs.statSync("bigbuck.mp4").size;
// Parse Range
// Example: "bytes=32324-"
const CHUNK_SIZE = 10 ** 6; // 1MB
const start = Number(range.replace(/\D/g, ""));
const end = Math.min(start + CHUNK_SIZE, videoSize - 1);
// Create headers
const contentLength = end - start + 1;
const headers = {
"Content-Range": `bytes ${start}-${end}/${videoSize}`,
"Accept-Ranges": "bytes",
"Content-Length": contentLength,
"Content-Type": "video/mp4",
};
// HTTP Status 206 for Partial Content
res.writeHead(206, headers);
// create video read stream for this particular chunk
const videoStream = fs.createReadStream(videoPath, { start, end });
// Stream the video chunk to the client
videoStream.pipe(res);
});
app.listen(8000, function () {
console.log("Listening on port 8000!");
console.log("Open chrome browser and paste this 'localhost:8000' to stream the video");
});