paint-brush
Node.js Tutorial: How to Build a Video Streaming Application in 10 Minutesby@alguerocode
10,720 reads
10,720 reads

Node.js Tutorial: How to Build a Video Streaming Application in 10 Minutes

by salah alhashmiMarch 4th, 2022
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

In this blog we will build a Node.js video streaming application in like 10 minutes. We will use Node.JS to create a video streaming app. The code is set to send a video video to the Frontend. The application is set up using Node.Js to stream a video stream. The video streamer is a simple web application. It is a web application that streams large amounts of data, or data that’s coming from an external source one chunk at a time, like arrays or strings.

Company Mentioned

Mention Thumbnail
featured image - Node.js Tutorial: How to Build a Video Streaming Application in 10 Minutes
salah alhashmi HackerNoon profile picture

Hi folks, in this blog we will build a Node.js video streaming application in like 10 minutes.


install Node.js in your computer

Prerequisite

  • install Node.js on your computer

What is streaming?

Streams are collections of data — just like arrays or strings. The difference is that streams might not be available all at once, and they don’t have to fit in memory. This makes streams really powerful when working with large amounts of data, or data that’s coming from an external source one chunk at a time.

Setup [ 1 ] - getting started

1 - create a folder and name it vido-streaming 2 - initialize npm in your project npm init -y

3 - install these packages dependencies.


#### npm install express

development dependencies.

npm install -D nodemon

add this script to your package.json file.

"start": "nodemon index.js"

Setup [2] - setup Node.js server

1 - create index.js file in your project root. 2 - add this code below


const express = require("express");

const app = express(); // setup express application
const PORT = process.env.PORT || 3000;

app.listen(PORT, () => {
  console.log("SERVER STARTED AT PORT: " + PORT);
});


This code starts web server using express framework and listening to port: 3000.

Setup [3] - serving html page

Now we want to serve an html page with a video element to the Frontend.


1 - create public folder in your project root. 2 - create index.html file in created folder (public) and add this html code.



<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>Home | Video Streaming</title>
  </head>
  <body>
    <video 
    controls 
    src="/video" 
    id="video-stream" 
    poster="/poster.jpeg" 
    width="700"
    >
	</video>
  </body>
</html>


  • controls : Specifies that video controls should be displayed (such as a play/pause button etc).
  • src : Specifies the URL of the video file.
  • poster: Specifies an image to be shown while the video is downloading, or until the user hits the play button.

Serving html file

we need to send the html page to the users. add this code below in index.js file.

app.get("/", (req, res) => {
try {
	res.sendFile(__dirname + "/public/index.html");
} catch (err) {
	res.status(500).send("internal server error occurred")
}
});

what that code does, is listening to get request in base URL of the application, when it get the response will be send file by using sendFile and first parameter is html file path.

note: __dirname is the root path of the current directory.

Serving poster image - setup [4]

Poster is image will be shown until the video is downloaded or the user clicks the video.


Note: you need to any image you want in a public directory that you make. See the code below


app.get("/:file_name", (req, res) => {
	try {
		res.sendFile(__dirname + req.params.file_name);
	} catch (err) {
		res.status(500).send("internal server error occurred");
	}
});

Streaming video - setup[5] and final

Import required node.js modules

When streaming the video we need to import two Node.js build-in libraries at the top of the file.


const  fs = require("fs");
const  path = require("path");


fs : file system module allows you to work with the file system on your computer. To include the File System module.


path: allows you to interact with file paths easily. The path module has many useful properties and methods to access and manipulate paths in the file system.

Setup video API function

Add this code before the Serving Poster Image function because Nodejs will go throw the express middlewares and if the requested URL is /video it will match the Serving Poster Image middleware, not the video middleware.


Note: you need to add a random video in the public file.


app.get("/video", (req, res) => {
// indicates the part of a document that the server should return
// on this measure in bytes for example: range = 0-6 bytes.
const  range = req.headers.range;
if (!range) res.status(400).send("Range must be provided");

const  videoPath = path.join(__dirname, "public", "video.mp4");
// extract video size by using statSyn()
const  videoSize = fs.statSync(videoPath).size;
// 10 powered by 6 equal 1000000bytes = 1mb
const  chunkSize = 10 ** 6; 

// calculating video where to start and where to end.
const  start = Number(range.replace(/\D/g, ""));
const  end = Math.min(start + chunkSize, videoSize - 1);
const  contentLength = end - start + 1;

// setup video headers
const  headers = {
"Content-Range":  `bytes ${start}-${end}/${videoSize}`,
"Accept-Ranges":  "bytes",
"Content-Length":  contentLength,
"Content-Type":  "video/mp4",
};

res.writeHead(206, headers);
// creating readStream (stdin).
const  videoStream = fs.createReadStream(videoPath, { start, end });

// create live stream pipe line
videoStream.pipe(res);
});

And then run npm run start. to see your work.

What is pipe() in streaming?

Streams make for quite a handy abstraction, and there's a lot you can do with them - as an example, stream.pipe(), the method used to take a readable stream and connect it to a writeable stream. the writable stream is the user we request him the data buffers.


Project source code: https://github.com/alguerocode/video-streaming

Follow me on GitHub: alguerocode


Thank you for reading.