Skip to content

Instantly share code, notes, and snippets.

@image72
Last active October 29, 2023 11:16
Show Gist options
  • Save image72/e26630a19f18925da5690864704573bf to your computer and use it in GitHub Desktop.
Save image72/e26630a19f18925da5690864704573bf to your computer and use it in GitHub Desktop.
// https://blog.logrocket.com/build-video-streaming-server-node/
router.get('/video/:id', (req, res) => {
const videoPath = `assets/${req.params.id}.mp4`;
const videoStat = fs.statSync(videoPath);
const fileSize = videoStat.size;
const videoRange = req.headers.range;
if (videoRange) {
const parts = videoRange.replace(/bytes=/, "").split("-");
const start = parseInt(parts[0], 10);
const end = parts[1]
? parseInt(parts[1], 10)
: fileSize-1;
const chunksize = (end-start) + 1;
const file = fs.createReadStream(videoPath, {start, end});
const head = {
'Content-Range': `bytes ${start}-${end}/${fileSize}`,
'Accept-Ranges': 'bytes',
'Content-Length': chunksize,
'Content-Type': 'video/mp4',
};
res.writeHead(206, head);
file.pipe(res);
} else {
const head = {
'Content-Length': fileSize,
'Content-Type': 'video/mp4',
};
res.writeHead(200, head);
fs.createReadStream(videoPath).pipe(res);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment