How can I stream a video in hono?

I want also to put a range header when user wants to put a specific time of video
5 Replies
Arthur
Arthur2w ago
Im curious aswell? How do we do this
Arthur
Arthur2w ago
I came with this:
No description
Arthur
Arthur2w ago
But it is slow tbh is there any better way (using bun ofc)
ambergristle
ambergristle2w ago
I’ve never tried, but have you taken a look at the streaming helper?
Arthur
Arthur2w ago
In the end I ame up with this @ambergristle
app.get('/arthur/videos/:day', async (c) => {
const filePath = `public/videos/arthur/${c.req.param('day')}.mp4`;
const file = Bun.file(filePath);
const stat = await file.stat();
const fileSize = stat.size;
const range = c.req.header('range');

if (range) {
const parts = range.replace(/bytes=/, '').split('-');
const start = parseInt(parts[0], 10);
const end = parts[1] ? parseInt(parts[1], 10) : fileSize - 1;
const chunkSize = end - start + 1;

const sliced = file.slice(start, end + 1);

return new Response(sliced, {
status: 206,
headers: {
'Content-Range': `bytes ${start}-${end}/${fileSize}`,
'Accept-Ranges': 'bytes',
'Content-Length': chunkSize.toString(),
'Content-Type': 'video/mp4',
},
});
} else {
return new Response(file, {
status: 200,
headers: {
'Content-Length': fileSize.toString(),
'Content-Type': 'video/mp4',
'Accept-Ranges': 'bytes',
},
});
}
})
app.get('/arthur/videos/:day', async (c) => {
const filePath = `public/videos/arthur/${c.req.param('day')}.mp4`;
const file = Bun.file(filePath);
const stat = await file.stat();
const fileSize = stat.size;
const range = c.req.header('range');

if (range) {
const parts = range.replace(/bytes=/, '').split('-');
const start = parseInt(parts[0], 10);
const end = parts[1] ? parseInt(parts[1], 10) : fileSize - 1;
const chunkSize = end - start + 1;

const sliced = file.slice(start, end + 1);

return new Response(sliced, {
status: 206,
headers: {
'Content-Range': `bytes ${start}-${end}/${fileSize}`,
'Accept-Ranges': 'bytes',
'Content-Length': chunkSize.toString(),
'Content-Type': 'video/mp4',
},
});
} else {
return new Response(file, {
status: 200,
headers: {
'Content-Length': fileSize.toString(),
'Content-Type': 'video/mp4',
'Accept-Ranges': 'bytes',
},
});
}
})
Mostly stolen from: https://medium.com/better-programming/video-stream-with-node-js-and-html5-320b3191a6b6

Did you find this page helpful?