Creating a simple HTTP server to serve a video file can be done using various programming languages and frameworks. For simplicity, we'll use Python, which has built-in modules that make this task straightforward. In this article, we’ll guide you through setting up a basic HTTP server using Python that listens on port 3000 and serves a video file.
Steps to Setup Project
Step 1: Make a folder structure for the project.
mkdir VideoHtmlStep 2: Navigate to the project directory
cd VideoHtmlStep 3: Initialize the NodeJs project inside the myapp folder.
npm init -yStep 4: Install the necessary packages/libraries in your project using the following commands.
npm install expressProject Structure:
The updated dependencies in package.json file will look like:
"dependencies": {
"express": "^4.19.2",
}
Approach
- Create an HTTP Server: Use Node.js to create a simple HTTP server listening on port 3000.
- Serve Index File: Respond to the root URL with an "index.html" file using
fs.readFile. - Handle Stream Request: On
GETrequest to/stream, respond with the video stream. - Set Headers: Use
res.writeHead(200, {'Content-Type': 'video/mp4'})for video response. - Stream Video: Use
fs.createReadStreamto read the video file and pipe it to the response.
Example: Implementation to create a simple http server listening at port 3000 to serve video.
<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible"
content="IE=edge" />
<meta name="viewport" content=
"width=device-width, initial-scale=1.0" />
<title>Video Stream</title>
</head>
<body>
<!-- autoplay: A Boolean attribute; if
specified, the video automatically
begins to play back as soon as it can
do so without stopping to finish
loading the data -->
<video controls autoplay width="500px" height="500px">
<!-- GET request to the stream route -->
<source src="/stream" type="video/mp4" />
</video>
</body>
</html>
// app.js
// Requiring express for routing
const express = require('express')
// Creating app from express
const app = express()
// Requiring in-built file system
const fs = require('fs')
// GET request which HTML video tag sends
app.get('/stream',function(req,res){
// The path of the video from local file system
const videoPath = 'Welcome-To-GeeksforGeeks.mp4'
// 200 is OK status code and type of file is mp4
res.writeHead(200, {'Content-Type': 'video/mp4'})
// Creating readStream for the HTML video tag
fs.createReadStream(videoPath).pipe(res)
})
// GET request to the root of the app
app.get('/',function(req,res){
// Sending index.html file for GET request
// to the root of the app
res.sendFile(__dirname+'/index.html')
})
// Creating server at port 3000
app.listen(3000,function(req,res){
console.log('Server started at 3000')
})
Step to Run Application: Run the application using the following command from the root directory of the project
npm startOutput: Your project will be shown in the URL http://localhost:3000/