Created
March 9, 2017 12:30
-
-
Save amalantony/81d3ff3b4c1a26da785c0639b7808802 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
app.get('/stream', (req, res) => { | |
const pathToVideo = "/path/to/video"; | |
fs.stat(pathToVideo, function(err, stats) { | |
if (err) { | |
if (err.code === 'ENOENT') { | |
// 404 Error if file not found | |
console.log('File not found!'); | |
return res.sendStatus(404); | |
} | |
res.end(err); | |
} | |
const range = req.headers.range; | |
if (!range) { | |
// 416 Wrong range | |
return res.sendStatus(416); | |
} | |
const positions = range.replace(/bytes=/, "").split("-"); | |
const start = parseInt(positions[0], 10); | |
const total = stats.size; | |
const end = positions[1] ? parseInt(positions[1], 10) : total - 1; | |
const chunksize = (end - start) + 1; | |
res.writeHead(206, { | |
"Content-Range": "bytes " + start + "-" + end + "/" + total, | |
"Accept-Ranges": "bytes", | |
"Content-Length": chunksize, | |
"Content-Type": "video/mkv" | |
}); | |
const stream = fs.createReadStream(pathToVideo, { start: start, end: end }) | |
.on("open", function() { | |
stream.pipe(res); | |
}).on("error", function(err) { | |
res.end(err); | |
}); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment