Skip to content

Instantly share code, notes, and snippets.

@juanpablocs
Created May 21, 2023 19:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save juanpablocs/414ac9587e59895f7b4fac733c95b776 to your computer and use it in GitHub Desktop.
Save juanpablocs/414ac9587e59895f7b4fac733c95b776 to your computer and use it in GitHub Desktop.

Video Stream with node.js

the part of code is express

app.get("/video", (req, res) => {
// indicates the part of a document that the server should return
// on this measure in bytes for example: range = 0-6 bytes.
const  range = req.headers.range;
if (!range) res.status(400).send("Range must be provided");

const  videoPath = path.join(__dirname, "public", "video.mp4");
// extract video size by using statSyn()
const  videoSize = fs.statSync(videoPath).size;
// 10 powered by 6 equal 1000000bytes = 1mb
const  chunkSize = 10 ** 6; 

// calculating video where to start and where to end.
const  start = Number(range.replace(/\D/g, ""));
const  end = Math.min(start + chunkSize, videoSize - 1);
const  contentLength = end - start + 1;

// setup video headers
const  headers = {
"Content-Range":  `bytes ${start}-${end}/${videoSize}`,
"Accept-Ranges":  "bytes",
"Content-Length":  contentLength,
"Content-Type":  "video/mp4",
};

res.writeHead(206, headers);
// creating readStream (stdin).
const  videoStream = fs.createReadStream(videoPath, { start, end });

// create live stream pipe line
videoStream.pipe(res);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment