Guest User

Untitled

a guest
Apr 12th, 2025
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.84 KB | None | 0 0
  1. const express = require('express');
  2. const fs = require('fs');
  3. const path = require('path');
  4. const app = express();
  5. const port = 3000;
  6.  
  7. // Serve static files from a 'public' directory (for HTML, CSS)
  8. app.use(express.static('public'));
  9.  
  10. // Video streaming endpoint
  11. app.get('/video/:filename', (req, res) => {
  12. const filename = req.params.filename;
  13. const videoPath = path.join(__dirname, 'videos', filename);
  14.  
  15. // Check if file exists
  16. fs.stat(videoPath, (err, stats) => {
  17. if (err) {
  18. console.error('File not found:', err);
  19. return res.status(404).send('Video not found');
  20. }
  21.  
  22. // Get file size
  23. const fileSize = stats.size;
  24. const range = req.headers.range;
  25.  
  26. // Handle range requests (for video seeking)
  27. if (range) {
  28. const parts = range.replace(/bytes=/, '').split('-');
  29. const start = parseInt(parts[0], 10);
  30. const end = parts[1] ? parseInt(parts[1], 10) : fileSize - 1;
  31. const chunkSize = (end - start) + 1;
  32. const file = fs.createReadStream(videoPath, { start, end });
  33. console.log("here")
  34.  
  35. // Set proper headers for streaming
  36. res.writeHead(206, {
  37. 'Content-Range': `bytes ${start}-${end}/${fileSize}`,
  38. 'Accept-Ranges': 'bytes',
  39. 'Content-Length': chunkSize,
  40. 'Content-Type': 'video/mp4'
  41. });
  42.  
  43. file.pipe(res);
  44. } else {
  45. // If no range requested, send the entire file
  46. res.writeHead(200, {
  47. 'Content-Length': fileSize,
  48. 'Content-Type': 'video/mp4'
  49. });
  50. fs.createReadStream(videoPath).pipe(res);
  51. }
  52. });
  53. });
  54.  
  55. // HTML page to display video player
  56. app.get('/', (req, res) => {
  57. res.sendFile(path.join(__dirname, 'public', 'index.html'));
  58. });
  59.  
  60. app.listen(port, () => {
  61. console.log(`Server running at http://localhost:${port}`);
  62. });
  63.  
Advertisement
Add Comment
Please, Sign In to add comment