Skip to content

Instantly share code, notes, and snippets.

@BerkeKaragoz
Created May 11, 2022 17:41
Show Gist options
  • Save BerkeKaragoz/a690a6366044ec9de52a16da6f788677 to your computer and use it in GitHub Desktop.
Save BerkeKaragoz/a690a6366044ec9de52a16da6f788677 to your computer and use it in GitHub Desktop.
Send video chunk by chunk
if (!req.headers.range) {
res.sendFile(fileAbsolutePath, { maxAge: '2 days' }, (err) => {
if (err) console.error(err);
});
} else {
const { size, blksize } = statSync(fileAbsolutePath);
const chunkSizeTarget = 10 ** 7 / 2;
const chunkSize = Math.floor(chunkSizeTarget / blksize) * blksize;
const start = Number(req.headers.range.replace(/\D/g, ''));
const end = Math.min(start + chunkSize, size - 1);
const contentLength = end - start + 1;
res.setHeader('Content-Range', `bytes ${start}-${end}/${size}`);
res.setHeader('Accept-Ranges', `bytes`);
res.setHeader('Content-Length', contentLength);
res.setHeader('Content-Type', `video/mp4`);
res.status(206);
const videoStream = createReadStream(fileAbsolutePath, { start, end });
videoStream.pipe(res);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment