How to make a video call app in node.js ? - GeeksforGeeks

05 Jan, 2021
For making a video call app, It is required that each and every client send their video and audio stream to all the other clients. So for this purpose we are using Peer.js and for the communication between the clients and the server we are using WebSocket i.e. Socket.io.
Prerequisite:1. Node.js: It is an open-source JavaScript Back-End technology. It has a package manager called npm– Node package manager which installs different packages very easily.
2. Express.js: It is a node.js server framework.
3. Socket.io:It helps us to create a real-time bi-direction event-based communication between the server and the client.
4. Peer.js: It helps us to send and receive the audio and video streams of the other clients.
Setting up the Environment: This is the very first step, here we are creating and initializing a new repository.
$ mkdir VideoCallApp 
$ cd VideoCallApp
$ npm init
Now, the next step is to install the required packages for our VideoCallApp.
Express : It is the server-based framework for node.js
ejs : It is a simple templating language that lets you generate HTML markup with plain JavaScript.
Socket.io : It manages the Websocket for event-based communication. 
Nodemon (optional): It automatically restarts the server when you save your project files.
uuid module: This module is used to generate a unique id. This will be used in this project 
Installing the required modules:
$ npm install express
$ npm install ejs
$ npm install socket.io
$ npm install nodemon
Now, we all set for the implementation part.
Implementation:
Step 1: Create a server file — server.js 
JavaScript
// Importing express moduleconst express = require('express'); const app = express();   app.set("view engine", "ejs");   // Calling the public folderapp.use(express.static("public"));   // Handling get requestapp.get("/" , (req,res)=>{  res.send("Welcome to GeeksforGeeks Video Call App"); });  // Listing the server server.listen(4000 , ()=>{    console.log("Server running on port 4000");) 
Execution command for server.js
node server.js
Now, If you open the local host i.e. localhost:4000 You will see the output i.e. — Welcome to GeeksforGeeks Video Call App.
Now, For socket.io we need to write some more code. Here, we added code for socket.io and we just change app.listen() to server.listen() methods.
Now we are all set for the client side development.
Javascript
const server = require('http').Server(app);const io = require('socket.io')(server);  server.listen(4000 , ()=>{    console.log("Server running on port 4000"););
Step2: Create two folders one is public and the second is views.
Project structure:
Now in views create an index.ejs file which contains all html code.
Here, we added three script files, first one is for peerjs, the second one is for socket.io and the last one is our main index.js file.
Index.ejs file
HTML
<!DOCTYPE html><html lang="en" dir="ltr">  <head>    <meta charset="utf-8" />    <title>Video App</title>    <style media="screen">        * {            margin: 0;        }          #videoDiv {            display: grid;            grid-gap: 10px;            height: 80%;            position: relative;            grid-template-columns: repeat(auto-fill, 300px);            grid-auto-rows: 300px;        }          #footer {            width: 100%;            height: 50px;            background-color: white;            display: flex;            justify-content: center;            flex: 1;            border-bottom: 1px solid grey;            margin-top: 10px;        }          button {            height: 30px;            width: 80px;            margin-top: 10px;            text-align: center;            border-radius: 10px;            outline: none;            border: none;            text-decoration: none;            background-color: red;            cursor: pointer;        }          video {            width: 100%;            height: 100%;            object-fit: cover;            border: 2px solid white;        }    </style>    <script type="text/javascript">        var roomID = "<%= RoomId %>"    </script>      <script src="https://unpkg.com/peerjs@1.3.1/dist/peerjs.min.js"        defer>    </script>          <script src="socket.io/socket.io.js" defer>    </script>          <script src="index.js" charset="utf-8" defer>    </script></head>  <body>    <div id="videoDiv"></div></body>  </html>
Note — you can create your own UI, I created a simple one.
Now in the public folder create an index.js file for your index.ejs file and write some code.
const socket = io('/');
const peer = new Peer();

peer.on('open' , (id)=>{
    socket.emit("newUser" , id);
});
So whenever the new user will get connected they will get a unique id through the peer.js and after that it emits a socket event for the server i.e newUser.
So to handle this event we need to add some more code in our server-side.
JavaScript
io.on('connection' , (socket)=>{    socket.on('newUser' , (id)=>{        socket.join('/');        socket.to('/').broadcast.emit("userJoined" , id);    });});
Now when this event occurs the server will tell all the other clients that the new user is connected.
Now we are going to take users audio, video streams and send that stream to another client. For this, we are going to use WebRTC here.
Code to take video and audio of the user-
Javascript
navigator.mediaDevices.getUserMedia({  video:true,  audio:true}).then((stream)=>{        // Some more code}).catch(err=>{    alert(err.message)})
Now we need to send the stream to all other clients, so let’s implement that part-
Here we have a peer.js method named as call. It will call the other client to send and receive streams.
Client 1: Client 1 will call client 2 as shown below.
Javascript
socket.on('userJoined' , id=>{  console.log("new user joined")    // Calling other client and sending our stream  const call  = peer.call(id , myVideoStream);  const vid = document.createElement('video');  call.on('error' , (err)=>{    alert(err);  })    // Taking the stream of the other client  // when they will send it.  call.on('stream' , userStream=>{      // addVideo is a function which append    // the video of the clients    addVideo(vid , userStream);  })
Client 2: let’s see how client 2 will respond to the client 1 call.
Javascript
peer.on('call' , call=>{      // Here client 2 is answering the call    // and sending back their stream    call.answer(stream);         const vid = document.createElement('video');      // This event append the user stream.     call.on('stream' , userStream=>{        addVideo(vid , userStream);    })    call.on('error' , (err)=>{        alert(err)    })  })
Now after sending and receiving the streams of both the clients the output will be – 
OUTPUT
Note — You can deploy it on any platform you want, In my case I deployed it on heroku.com
For source code please click here, Also it is a basic one you can modify it as you want.
Node.js
Socket-programming
Technical Scripter 2020
Node.js
Technical Scripter
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between dependencies, devDependencies and peerDependencies
How to connect Node.js with React.js ?
Node.js Export Module
Mongoose Populate() Method
Mongoose find() Function
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript