I have a Node.js backend server, which as soon as it receives a request will create a readstream from the fs module to a video in the films folder, and pipe this to the response.
The browser automatically creates a video tag and streams the film, however, I may wish to add some CSS styles to the video tag, so how would I include some classes or id's on the video before the stream is sent, or is this just not an option?
Code is below:
const getFilm = async (req, res) => {
let ranges = req.headers.range;
let film = path.join(__dirname, "..", "films", "IMG_2694.mp4");
let size = fs.statSync(film).size;
if(ranges) {
let [ start, end ] = ranges.replace('bytes=', '').split('-');
start = parseInt(start, 10);
end = end ? parseInt(end, 10) : parseInt(size-1, 10);
res.setHeader('Content-Range', `bytes ${start}-${end}/${size}`);
res.setHeader('Accept-Ranges', 'bytes');
res.setHeader('Content-Length', (start - end) +1);
res.setHeader('Content-Type', 'video/mp4');
res.statusCode = 206;
let reader = fs.createReadStream(film, {start, end});
reader.pipe(res);
} else {
res.setHeader('Content-Type', 'video/mp4');
res.setHeader('Content-Length', size)
res.statusCode = 200;
let reader = fs.createReadStream(film);
reader.pipe(res);
}
}