Implement res.sendVideo fn #5770
Replies: 4 comments 4 replies
-
Hey @binarykitchen, I don't think it has been brought up before but as someone who has worked quite extensively on both the server and client with video content (before joining Netflix the startup I was at was an SVOD service which pivoted to a live streaming service) I don't think it is something which can easily be taken on. If you could bring some more examples of use cases you have seen where folks incorrectly used |
Beta Was this translation helpful? Give feedback.
-
Thanks @wesleytodd, here's a "horrible" draft example of what I'm after: function streamVideo(
videoPath: string,
type: string,
req: Request,
res: Response,
next: NextFunction,
) {
try {
log.debug(`Streaming video ${videoPath} now ...`);
const stat = fs.statSync(videoPath);
const fileSize = stat.size;
const range = req.get("range");
let status: number;
let contentLength: number;
const head = {};
const streamOptions = {};
if (range) {
const parts = range.replace(/bytes=/, "").split("-");
const firstPart = parts[0];
if (firstPart === undefined) {
throw new Error(`Unable to grab the first part of the video file ${videoPath}.`);
}
const start = parseInt(firstPart, 10);
const end = parts[1] ? parseInt(parts[1], 10) : fileSize - 1;
// Aka chunk size
contentLength = end - start + 1;
status = 206;
head["Content-Range"] = `bytes ${start}-${end}/${fileSize}`;
head["Accept-Ranges"] = "bytes";
streamOptions["start"] = start;
streamOptions["end"] = end;
} else {
// Unable to split it in ranges, so as a fallback, just stream the whole
status = 200;
contentLength = fileSize;
}
const stream = fs.createReadStream(videoPath, streamOptions);
head["Content-Type"] = `video/${type}`;
head["Content-Length"] = contentLength;
res.writeHead(status, head);
stream
.pipe(res)
.on("close", () => {
next();
})
.on("error", (err) => {
next(err);
});
} catch (exc) {
next(exc)
}
} Something like that. It can be improved further, e.g. grab the mime type of the file and allow streaming any multimedia files, not just videos. |
Beta Was this translation helpful? Give feedback.
-
Oh, good, analysis @krzysdz thanks. So it's because I'm using HTTP2/SPDY servers? Hmmm, this package hasn't been maintained for a long time and I do not see a need to use it in my app. Will consider removing it ... |
Beta Was this translation helpful? Give feedback.
-
I concur. SPDY was the troubled child. With classic Node.js HTTPS servers and Thanks for the good analysis and feedback, everyone. |
Beta Was this translation helpful? Give feedback.
-
I see too many use the sendFile fn the wrong way for delivering videos to the clients.
Why not implement a new
sendVideo()
fn with proper streaming and content-range calculations? Wondering if this has ever been raised before?If not, do you think a PR would make sense and it's the right place here to do so?
Thanks for your thoughts.
Beta Was this translation helpful? Give feedback.
All reactions