How to create a simple http server listening at port 3000 to serve video ?
We can serve video to the browser/front end using nodeJS with the help of “express” and the in-built nodeJS file system “fs“. Here we would use the HTML video tag to view the video on the webpage. We would use express for routing purposes. We would send the video bytes by creating a read stream and piping the res Object to it. Let’s walk through step by step.
Step 1: Create an “app.js” file and initialize the project with npm. Also, keep the video file that you want to stream in the same folder.
npm init
Step 2: Now install express and create the “index.html” file.
npm install express
Project Structure: It will look like the following.
Project Structure
Here “Welcome-To-GeeksforGeeks.mp4” is the mp4 file that we want to stream.
Step 3: Let’s code now “app.js” file. The GET request to ‘/stream‘ sends the video as a readable stream. The root of the app loads the “index.html” file. We use res.writeHead() function to send the status message as 200 which means OK and the content type is mp4/video. We would now create a read stream using the fs.createReadStream() function to send the video as the readable stream for the HTML video tag.
app.js
const express = require( 'express' )
const app = express()
const fs = require( 'fs' )
app.get( '/stream' , function (req,res){
const videoPath = 'Welcome-To-GeeksforGeeks.mp4'
res.writeHead(200, { 'Content-Type' : 'video/mp4' })
fs.createReadStream(videoPath).pipe(res)
})
app.get( '/' , function (req,res){
res.sendFile(__dirname+ '/index.html' )
})
app.listen(3000, function (req,res){
console.log( 'Server started at 3000' )
})
|
Step 4: Now we will code the “index.html” file. Here we are using the controls attribute for providing various controls of media-player in the video tag. And the autoplay is a Boolean attribute by which the video automatically begins to playback as soon as it can do so without stopping to finish loading the data. The src attribute of the HTML video tag is ‘/stream’ as defined in the app.js file.
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 >
< video controls autoplay width = "500px" height = "500px" >
< source src = "/stream" type = "video/mp4" />
</ video >
</ body >
</ html >
|
Step 5: Now run the app using
node app.js
Output: Head over to your browser and enter http://localhost:3000/
Output
Last Updated :
16 Feb, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...