Real-time Video Streaming with Node.js and HTML5

Learn how to stream real-time video using Node and HTML5. This tutorial will walk you through the steps of setting up a video streaming server and client-side HTML

To stream video using Node.js and HTML5, you can use the express framework to create a web server that serves video files, and the HTML5 video element to display the video in the browser. Here's a basic example of how to do this:

On the server-side (Node.js), you can use the express framework to create a route that serves video files:

 const express = require('express');
const app = express();
const path = require('path');

app.use(express.static(path.join(__dirname, 'public')));

app.get('/video', (req, res) => {
  const videoPath = 'path/to/your/video.mp4';
  const stat = fs.statSync(videoPath);
  const fileSize = stat.size;
  const range = req.headers.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 file = fs.createReadStream(videoPath, { start, end });
    const headers = {
      'Content-Range': `bytes ${start}-${end}/${fileSize}`,
      'Accept-Ranges': 'bytes',
      'Content-Length': chunkSize,
      'Content-Type': 'video/mp4',
    };
    res.writeHead(206, headers);
    file.pipe(res);
  } else {
    const headers = {
      'Content-Length': fileSize,
      'Content-Type': 'video/mp4',
    };
    res.writeHead(200, headers);
    fs.createReadStream(videoPath).pipe(res);
  }
});

app.listen(3000, () => {
  console.log('Server is running on port 3000');
});

In this example, the express framework is used to create a web server that serves static files from the public directory. The /video route is used to serve the video file, and the range header is used to allow the client to request specific parts of the video file.

On the client-side (browser), you can use the HTML5 video element to display the video:

 <video controls>
  <source src="http://localhost:3000/video" type="video/mp4">
</video>

In this example, the src attribute of the source element is set to the URL of the /video route on the server. The type attribute is set to the MIME type of the video file.

Note that this is just a basic example and you'll likely need to customize the code to suit your specific use case. Additionally, you may want to consider adding error handling, authentication, and other security features to ensure the safety and privacy of your users.