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.
Step 2: Now install express and create the “index.html” file.
npm install express
Project Structure: It will look like the following.
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.
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.
Step 5: Now run the app using
Output: Head over to your browser and enter http://localhost:3000/