Last active
October 29, 2023 11:16
-
-
Save image72/e26630a19f18925da5690864704573bf to your computer and use it in GitHub Desktop.
stream video https://www.smashingmagazine.com/2021/04/building-video-streaming-app-nuxtjs-node-express/
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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