Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const express = require('express');
- const fs = require('fs');
- const path = require('path');
- const app = express();
- const port = 3000;
- // Serve static files from a 'public' directory (for HTML, CSS)
- app.use(express.static('public'));
- // Video streaming endpoint
- app.get('/video/:filename', (req, res) => {
- const filename = req.params.filename;
- const videoPath = path.join(__dirname, 'videos', filename);
- // Check if file exists
- fs.stat(videoPath, (err, stats) => {
- if (err) {
- console.error('File not found:', err);
- return res.status(404).send('Video not found');
- }
- // Get file size
- const fileSize = stats.size;
- const range = req.headers.range;
- // Handle range requests (for video seeking)
- 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 file = fs.createReadStream(videoPath, { start, end });
- console.log("here")
- // Set proper headers for streaming
- res.writeHead(206, {
- 'Content-Range': `bytes ${start}-${end}/${fileSize}`,
- 'Accept-Ranges': 'bytes',
- 'Content-Length': chunkSize,
- 'Content-Type': 'video/mp4'
- });
- file.pipe(res);
- } else {
- // If no range requested, send the entire file
- res.writeHead(200, {
- 'Content-Length': fileSize,
- 'Content-Type': 'video/mp4'
- });
- fs.createReadStream(videoPath).pipe(res);
- }
- });
- });
- // HTML page to display video player
- app.get('/', (req, res) => {
- res.sendFile(path.join(__dirname, 'public', 'index.html'));
- });
- app.listen(port, () => {
- console.log(`Server running at http://localhost:${port}`);
- });
Advertisement
Add Comment
Please, Sign In to add comment