Created
July 7, 2019 21:01
-
-
Save kmaher9/0f9813421b601306133bcbd386e05083 to your computer and use it in GitHub Desktop.
This file contains 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
const fs = require('fs') | |
const video = './videos/sample.mp4' // source video | |
let stat = fs.statSync(video) | |
let range = request.headers.range // will be undefined on first request | |
if (range) { // if the user is requesting to scrub to a point in the video | |
let [start, end] = range.replace(/bytes=/, '').split('-') // the incoming range typically looks like bytes=3214-5435, so extract the numbers out from the request | |
start = parseInt(start, 10) // check we are dealing with an integer | |
end = end ? parseInt(end, 10) : stat.size - 1 // a request can be for a segment, or could be 'bytes=324-' idicating from here, until the end of the video. Therefore end can be undefined. | |
// if it is undefined set it to the length of the video content | |
response.writeHead(206, { // 206 tells the browser to expect a partial request, so a continuation of a stream | |
"Content-Range": `bytes ${start}-${end}/${stat.size}`, // the current requested segment | |
"Accept-Ranges": "bytes", | |
"Content-Length": (end - start) + 1, // not video size, but instead the actual length of buffer | |
"Content-Type": "video/mp4" | |
}) | |
fs.createReadStream(video, { start, end }).pipe(response) // only stream part of video from given timestamps - handles request for us | |
} else { // a new first time request would hit this point, since there is no range to scrub to. Therefore just begin a new stream | |
response.writeHead(200, { | |
"Content-Length": stat.size, // the total length of the content | |
"Content-Type": "video/mp4" | |
}) | |
fs.createReadStream(video).pipe(response) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It's very awsome