uh Hello friends welcome to this video so in this video we will be actually be building a Facebook me messenger
chatting application group chatting application inside socket.io in nodejs
and express and uh you can actually see this is actually the application and if
you land on this group chat application you need to enter your username you can pick any username right here and all
this information we will be storing it inside mongodb database I've already created a database called as group chat
if you see right here this is a database and right after I select my username I
can give any username of let me give my name and click on okay and uh now you
will basically see this message will there goam you can see the username that
you enter has successfully joined the chat notification message will be sent to all the clients which will be
connected to this uh application this chat so this is actually the URL we are
running it to Local Host 3000 and the beauty about socket.io is that you can
actually open this in different windows and again this will be another client
another socket so you may just imagine whenever you deploy this application
whenever someone opens it's a new connection so it's a different user which here you can provide another
username and now as I provide the user username you will actually see in this
window also that notification message will also say that John has joined the chat so it is broadcasting this event in
to all the clients that certain event has happened a new client has joined the chat so side by side let me show you the
chatting here and let's suppose if I send some kind of message right here from this window you will now see it
will be broadcasted to both the clients you will see now now this is actually the username followed by the message
text message so here I will say hello and now send it and now you will see
this is actually the username that you selected in this window and now you can see so these are two different people
talking to each other because I'm on the same computer so I just open new two new
browser windows which are actually communicating with each other so now we also have the option to actually send
image PDF or videos any sort of attachments right here you will see choose file
button is there and right here you can actually select any images that you want
to send so let me select this image and click on send you will see in both the
windows the image will be sent and if you see it's a fully fleshed image you can open this image in new tab so this
image is sent right here and uh in this way you can send any image in the chat window you can see that so we are
actually storing all these images in the uploads directory if you see these images are stored in the server using
malter and also we are storing the paths in mongodb database so these are all the
tables which will get created these are the messages table these are the users table which are there
in so there are currently two users chatting with each other you can see that the
username and these are the messages that they have exchanged you will see this is a text message
this is the image message here we are storing the path of the image file right here so similarly you can send uh any
file uh it did not have to be image you can send PDF file any file that you want
to send SVG file you can even send right here so if you click Send so now if you
see dasvi file is also showing right here so if there if this is not if this
is not a image file in that case the file will have a downloaded link so
you will see that we are sending a webm file and now you will see in both the
windows the video file has been sent and now anyone can click on it and they can
download their download this file inside their computer and view this file so in
this way you can exchange messages you can exchange files as well in this group
chatting application and we also also have notification messages so let's suppose if someone leaves this chat
there will be this notification message that John has left the chat similarly
whenever someone Jo joins it once again we will again get this message that John
has joined the chat so all the basic functionalities of a group chatting application that you see online the
notification messages you can exchange media as well so all such things you
will see that and uh you can just connect as many clients as you want you can have a third client
connected so we are opening another new window so again it will be a same user
connected because we are storing the username in local storage that's why you will not see every time the alert box so
if you uh just opening the application for the very first time then we are
actually storing this username information in the local storage and then we are actually
inserting in the database so you will see the local storage right here and uh
right here the username value is stored in the local storage so every time we are not showing user the alert box to
actually enter the username for the very first time they select the username and we just uh store it in local storage and
then we store it in the users table in the database so this is the logic and we
are storing media files right here you you see in the uploads directory
so now in the next section guys I will show you how to code this application from scratch and uh if you are watching
it for the very first time please hit that like button subscribe the channel as well and uh for building this we are
actually using some of the Technologies which is socket.io which is a web RTC
Pro library for implementing these uh bidirectional low latency communication
between the client in the server for building these chatting applications so we are using this socket.io library and
this is their official Doc documentation and the website you can read more about it and then we are actually using
expressjs for building the backend server so just you can write Express
this is the backend server we are using and uh in nodejs and for uploading files we are
using this Library called as molter which allows you to actually store all
the images that you sent in the chatting application so 4 million weekly downloads and also we are using ejs
template engine which is allows you to actually render uh JavaScript templates inside
your HTML so 13 million weekly downloads so these are all the packages we are
using it EGS Express molter socket.io and lastly we are using Mongo's package
to actually connect with the mongod database which acts as a driver so it
actually is a library which allows you to connect with the mongodb database and store all this information so 2 million
weekly downloads so now in the next section we have start coding this Facebook Messenger group chatting
application so if you need the full source code the link is given in the description you can go to my website
procore.com and purchase the full source code with full documentation and support from me so the link is given you will
actually get a zip file after the payment is done you will be redirected to Google Drive where you can actually
get all the source code files which are there in this tutorial this is a custom CSS so I will not write all the codes
such as this custom CSS because it's not about CSS this tutorial so it's better
that you purchase it to actually better follow along with the tutorial so I will be now be seeing in the next section uh
now to get started guys I am navigating to the project directory and right here
I will simply make a new folder and I will simply call this as Facebook
Messenger clone and I will navigate to this
folder CD into this Facebook Messenger clone
let me see what I call this
Facebook so now I will open this folder inside vs code so first of all what we
need to do we just need to create a empty package.json file with the default options because we need to initialize
our so we'll simply say npm in it- F so
this will actually create your package.json file if you see on the left hand side now we need to install the
modules which are required for this application so we will install the Express package for our web server we
will install the socket.io EGS mongus and malter so all
the five packages I talked about in the previous section Express for backend server socket.io for implementing the
chatting functionality for bidirectional communication between the client and the server ejs is a template engine for
rendering JavaScript in HTML for interacting with mongodb database and
molor for uploading image files these are the five packages which are required
so simply install these so after that we will start writing
the starting point of the application so write in the root directory create your index.js file
just create your index.js
file uh now guys we will actually create the starting point of the application which is in the root directory create
your index.js file and right inside this file we will actually import all the
pack packages first of all and we will simply start the express
server first of all we will require it and for working with socket.io we do
need to include the socket IO package as well we require it
socket.io and uh the thing with socket.io it doesn't work with Express
directly you can't pass the reference of Express directly in socket.io you do need to actually include the built-in
package of HTTP which is in there in nodejs for creating HTTP server so you
just need to require the buil-in module of HTTP and then we can actually pass the
reference so we will create a new app of Express and uh then we will be creating
a server which will be HTTP do create server and here you need to pass your
reference of this app app variable right here in this uh app right
here so you can't directly pass socket.io to express you do need to do
this like this and then we'll be creating a input output variable of
socket.io and pass this server like
this this is a thing with socket.io and you just need to do right like this and
now we can start this HTTP server which have the express you can listen this on
port number 5,000 and just in the Callback you can give a console lock
statement that app is listening on for 5,000 and now in the development
package.json we can add a script Dev script and which will start
nodon index.js nodon if you don't know it restarts your server every time if
you make a change you can install it globally like this npmi dasg nodeb so it
will restart your server whenever you make any sort of changes and we simply
added a script Dev Dev script nodon index.js so we can simply now npm run
Dev so automatically it will restart the server you will see app is listening on
Port 5,000 and you'll actually console loog statement is coming so now after we
did it is done we just need to require the Mongo's library for actually
connecting it to the mongodb database so we just need to require this library and the connection setup is
pretty simple we are using a community based UI GUI which is called as mongodb
Compass you can even download this on Google just type mongodb
Compass so it's available for Windows and I think it's available it's
a crossplatform software so you can even try out mongodb Atlas which is online version but
mongodb it's available for you can see Linux as well Mac every operating system
it's available so once you install it you can uh start this and this will actually give you this connection string
that we need this mongodb colon // localhost this is actual port number it
listen on uh let me start this zoomit application so that I can zoom in on the
actual thing so by default the mongodb listens
on this port number which is 27017 this is the connection stream now you need to
click this button of connect so after that you can click on this create a
database so we can create a database called as
Facebook messenger and then we just need to give
it a sample connection so you can give any name of to your table or collection
click on create database so this is required to actually create a basic collection whenever you're creating a
database so once you create your database you will see it it will created like this so now we can actually connect
to this database by using uh we will just write a comment right here mongodb
connection code so we can simply say
so you can just you can even write it in a different file but I will for
the sake of this tutorial I will write it in this same file so mongodb colon K
local has 27017 followed by your database name so
Facebook messenger and then we can use new use
new URL parcel to be true and use
unified topology to be true as well
so if you do this uh you will actually
see so nothing is giving error so now we are successfully connected to the
database so after we do this we just need to create a public folder right here and
here we'll be just storing the St static assets so you can just create uh CSS
folder and then we can create the JavaScript
folder inside this public so this one these are two different folders uh first
one for storing the CSS files and then the second one for storing the
JavaScript files which are on the client side so these are two different folders
and the third folder we will create it for actually storing the media files so
whichever media files that you upload in chatting application you'll be storing it in the uploads folder this is a
directory structure and right after that we will be actually creating a views
folder where we'll be storing the index. ejs file which is a template engine that
we installed it so we can now set this template engine right
here you can simply say app. set view engine and and we can set that view
engine to be EGS that we installed apart from that we also need to make this
directory which is of the public directory as static so for that we'll use a app.use and pass the middleware
express static function that is provided by Express to actually make any directory as public we are making this
public directory as static and also we need to include Express Json these two
middle and express. URL encoded extended to
false so this is necessary while we are working with forms in order to get the
values the user selects in the form so these two things are necessary this is
specifically done for body parsel middleware which is built in an Express just write these two middleware
lines so now after that we also need to set up the malter so we can require this
malter package as as well after that we also need to set
up the monitor storage engine so right here you can set up it after doing this
you can simply say
configuring molter so we can just make a storage engine so molter provides you with the
dis storage so right in the inside this it
takes two options first is the destination destination object
state so where you need to store your files so this will be a call back function and you'll be storing it
inside the public SL uploads directory that we created and the second option is
take is the actual file name what file name that you want to give to your uploaded file so we'll be giving it
a random name by using date do now and whatever is the path of the file
so in order to get the path we will be using the buil-in package provided by
nodejs which is path so just require it and right inside
this method this module contains a method called as path. extension name and we'll
be getting the original name of the file using this property file. original name
that sols with this will be the random file name which will get assigned this is your storage you can directly pass
the storage to molter you can create a upload variable
and you can simply pass to molter whatever the storage that we assign you can assign it to light this is just a
configuration code for molter if you have ever worked with molter you will see what I'm doing right here we
configuring the molter to where you need to store your files and which file name
and and then lastly we are providing this the storage object to the storage
this is your middleware which is ready now you can actually make some routes
for our application so first of all we'll make a get route so let's whenever
someone goes to the homepage what sort
of information that you see on the screen so we have the app variable right here we can simply
make a get request right
here so when someone goes to the homepage we will be loading this template of
EGS response. render index so now in the index. ejs file we
can write any valid HTML code so you can change the title to Facebook Messenger
group chat so we you can simply write a simple heading on the
screen so it will automatically restart and if you navigate to Local Host 3000
in the browser hopefully you will see sorry I'm running it on Local Host
5000 you will see this heading right here Facebook Messenger so we are
successfully loading this index. EGS template so now the thing we need to do
right here uh we need to include socket.io in the client side as
well so for we will be doing this in the next
section so now guys in this section we will be importing the
socket.io package at the client side as well so you will see we have imported
this at the server site in Express we are including this right here HTTP create server we have
made a backend server and then we are using this input outputs we are passing
this reference of this server to the socket.io so we successfully configured
this on the server side so now to do it on the client side socket.io do offer a
library we need to include this script T and uh we can include this/ socket
SL so/ socket.io socket.io dogs so if you see in your
nodejs module folder whenever you install the socket.io package this will be present if you see
this is the folder which is present so we are directly loading this/ socket.io
and inside this we are simply loading this
file it does Prov provide you with this client JS automatically it is present
socket.io so you can directly open this path in the file I think it is
present Local Host 5000 socket.io /o. io.js if you directly open
this path in the browser it will give you this minified code right here this is actually the client library of
socket.io that we are loading it indirect in using the script tag so now
after that we will be loading another script this time this will be the custom
JavaScript which will be located in the JS folder and uh it will be I will call
this as client JS so now I will go to the public directory and
uh in the JS folder you'll create a file called as client JS this file uh is uh
will this will contain the JavaScript code which will be executed so we will
be simply be adding the event listener so this event listener is Dom content loaded so when all the elements are
loaded we just need to load the
socket.io library for loading it it's very simple we create a variable and
initialize it to input output So it's b directional communication with between
the client and the server and socket.io provide both the libraries at the server side and the client side so we can
console loog this information socket so if you see if you connect it if you open
your application and uh inspect element go to console you
will see this actually returns a object about the socket socket I told you it's
a client it's a it refers to any individual that is opening a browser it
refers it has various properties like this the ID of the socket or the client
of the browser which basically contains browser information so each and every browser so
now we can also bind events we can
uh send events emit events between client and server so by directional
communication so you can simply write here input output and it does provide you on function so
the there is built-in events right here which is connection event so whenever a
new client is connected this event will automatically fire and a new socket will
be connected so we can actually say a message on the console and we will say a
new client is connected so this console log message will come in the right right
in the server client you will see that a new client is connected similarly we
have another option whenever someone leaves we also we can bind
it to the socket so socket. on disconnect event is also pre-built so
let's suppose if someone leaves the chat you can just console loging
message a client disconnected
so this will only fire whenever someone Clos the browser you will not see only
this message is showing right here so again if someone opens the browser for
the second time it will treat it as a new client you will see two messages are
there now if I close
it so if I close this you will now see a client disconnected this is B
directional communication happening between the client and the server using socket.io and using this communication
we will build our chatting application so now in the next section or I can
develop the interface in this section itself it's very simple uh I will not
write the CSS code so what I will do uh I do have
the CSS code which is available inside so what I will do
uh it's available inside uh this CSS folder so this is Styles
file right here so what I will do I will simply copy this and paste it so all the source code is given in
the description so you can purchase it this is a styles.css file and right we
can directly up include this file
which is in present in the CSS folder styles. CSS and now uh we can directly write the
HTML right here we will have an diff which will have the chat container div
inside this we will have a simple form where the user can write
messages or select attachments as well so message form we have given an ID and
then inside this we have the input type first of all it will be a hidden field
and we will be giving a name attribute of username and an ID as well of username so this EV this input field
will not be seen by the user it just for storing this information in local
storage and the second one will be for input type text here we will allow the
user to enter the message text message we'll give it a name attribute of
message and an ID of message as well we give it a placeholder enter or type a
message and if you refresh you will actually see we have already pre-made the classes
you will see this input field is added right here and after this we will simply have
another input type file and we'll give it a name attribute of file and ID of
file as well so here we will allow the user to actually upload files so a choose file
button will be added right here lastly we will have a button to actually submit
the form so I will call this as send button you will see a green button is added
right here send button this is a chat container right here so this is all which is available
in the user interface now in the next section we will start writing the code for
implementing this chat application so I will be seeing you in the next section uh now guys in this
section we will start building the functionality in the chatting application first of all we will tackle
the username so whenever you land your application we will allow the user to actually select the username which will
be used in the chatting session and for doing this we actually
need to include a third party package sweet Alert 2 which will will actually show you a alert message where the user
can enter the so it's actually an alternative to the normal alert boxes
that you see in the browser it's a very good uh alert Library so we can simply
include their CDM so installation go to installation
and simply include this script tag and go to your HTML file index.
EGS right right at the top side include the CDN right here
now you can use the sweet alert package inside your CLI JS so first of all what we will do we
will get get reference to all the elements in the Dom so we'll be
getting reference to the username
input so document. get element by ID usern name we have given an ID in the
HTML and that's all for now we will only be tackling the usern name so that's all
we'll be declaring a global variable we will be keep track of which username the user
selects so we have declared a variable right here so after that as I already told you
we'll be storing the username in the local storage so here we'll have if condition if local storage has an
existing user has has an existing idid so this is actually called as key
parameter in local storage so so here we are checking in this if condition that if the username is already present in
the local storage then we will get that username and store it in the variable
local storage dot get item username so we are getting the item
from the local storage and assigning it to the username input
username and right here this is actually the client site we are sending an
event to the server site so we can send events as I already told you in
socket.io from server to client or client to server it's a b directional protocols web RTC so socket the variable
that we declared you will see it has input output reference it contains a
function called as Emit and here we can name your event whatever so in this case
I will call this as join and we will pass a payload in the
second AR argument in this case we will pass the username you can pass an object you can
pass an array but in this case we will pass a variable which is the actual username like this now we need to catch
this event in the server site so right in the this block of code where the
client is connected so we'll simply catch this event in the server site by
simply invoking socket. on and we here we can catch
events which the client sent so here we are sending the uh event called as join so we can
catch this event in the server site called join so we'll be asynchronously
we're getting the username right here so whatever username the user passes we will get this in the server site we are
console logging it so it's very
simple so right here we will simply if the username is not present in the local
storage in the else condition we will show a alert
message so for the alert alert message you'll use the sweet alert so as W it
contains a function fire and it basically just expect you to give it a
title so we'll simply say enter use username we'll give it a input field
where the user can enter a text value and you'll simply input placeholder
you'll simply say to the user usern name input
validator so here the value will come after you enter it in this variable
so you'll simply check if the username is not ex typed by the user in that case
you will show message to the user that you need to enter you need to write
something so if the user doesn't write something you'll just return a
message so this function returns a promise you can handle this using dot
then and after that it Returns the value result and now you'll simply if the
result do is confirmed property comes out to be true in this case this simply
means that if the user clicks the okay button after entering the username this
condition will evaluate to True after that we be getting the username value using result.
value again we'll be doing the same process setting the username input do
value to be the actual username that is selected and also you'll be setting this
time in the local storage you'll use set item to actually set the item in the
local storage we will put a key parameter username and pass username like this and lastly we need to again
emit socket. emit again call the same event and pass the
username so now if the user clicks the cancel button in that case you will simply say
username is required to join the
chat and then you will just
uh reload the page or I think it's not necessary for now let me just see what
happens if I land on the page you will see automatically it will detect no
username is present in local storage so you will actually see a alert box of
sweet alert to and here you need to enter your username so whatever I enter right here
I will get this in the console server site console so for that I need
to yeah so we are actually listening on Local Host 5,000 in the so whatever I
type right here whatever username I type you will see I'm getting it in the
console so the interaction is happening
successfully from client to server we are returning the information from the browser of the user to our server so
this is the communication which is happening directly if you see from client and the server
so now in the next section guys we will look at how to actually set this information in
the database uh now guys we will be writing the server site code to actually
save that username in the mongodb database so whatever username user right
in this event this event right here after console logging it we need to
actually store this username in the database so for doing this we will simply say await as this is a async
function we will simply say user and for actually uh saving this information we
do need to actually create a schema first of all so write in your root directory create a models
folder so models will be the actual data which will be storing it so first of all
create user.js so this will actually hold information
about the user so we'll be importing the package we will require it and for
constructing the schema we will be declaring a variable user schema new
Das schema and actually it contains an object username we'll be
storing it which is of type string and we'll also be storing the Tim stamp as
well which is of type date and uh the default value of it will
be the the current date and time date.
now and then we just need to create the collection using this model using the
schema so do model and we'll name our collection as user so this user
collection will be created using the schema that we provided now lastly we just need to
export this file so module. exports. user
so similarly you need to create another file for messages as well so the number
of messages will be storing it we do need to create their own schema for that also so again require the
library and here we need to select the schema
for so the messages so each message will comprise
of so it has each message will have a username which username has sent the
message and then the actual message which will also be a type string and if
any image or file has been selected by the user then that file will also be of
type stream file type will also be of type stream the extension of the image
file and lastly the Tim
stamp which is of the type date when the message is sent so default
value will be date do now so we don't need to manually pass
the time stamp it will take the default value the current date and time and
uh the same thing after we need to actually create the table for this
also do model and call this table as
message using the schema that we provided and then we need to export this
file as well module exports message so now we have both these model
files ready user and messages so now we can successfully import this
file by simply calling
so first of all what I need to do
uh okay so right here we will be creating a new object of that
user model class so it will automatically get imported vs code will
automatically import from Models folder if you see we creating a new object of
it and passing right here the actual username value in the cly bracket you'll
see that and then we will simply say socket. username is equal to username we will
initialize a property to the current socket we will add this property of username to the actual past
username and then we will again now emit a event to the
client similarly when we send information from clients to ser now we can send information from server to
client so for now we will use input. I IO variable which is This Global
variable so whenever you want to send information from the server to the client we'll use
I/O not socket so input output. emit so this will some emit this event to all
the clients which is connected so this will to all clients which are connected
it will actually broadcast this event that this username is join the
chat so we are sending this payload as a second argument now we need to catch this in the client
site so how we can catch this it's very easy so right here if you
see we have this uh outside this if condition we will simply
say socket Doon user joint and we'll get the username the
user uh server passes So based upon this event now we
can update the UI we can actually have a message on the chat
board that this username has been joined so we will simply create a dynamic
element of Li and we'll simply say new message
do inner HTML we will simply say in back teex
symbol that this username
has joined the chat and after that we need to add this
message to the message container so we do need to get a
reference to the message container
like this so we need to I think we haven't
added in the you'll see uh in the chat container just before
this we do need to add uh HTML for
this where we'll be storing the massage Mees so we will just had a UL
element just unordered list we will give it an ID of messages we just targeting this UL
element and right inside this messages
container we will append this
child of new
message that's all so now if you see guys if you refresh
now so it is saying that message container is not
defined I think some error is there uh message
container message container uh sorry let me call this correctly
message container so now you will actually see a
message on the screen John has joined the chat so it already detected that uh
a local storage variable has been set you'll see that the username that you
give if you check your database a table will be created or the user table and it
has a value if you refresh it it doesn't have
any value let me see what is the problem uh we are getting the message but we
haven't inserted information in the database
so think I need to refresh it or something wrong with the connection
if you see we are actually getting this information in the
console and the index.js
okay we forgot to call the save method guys that's why the problem is
occurring okay after we initialize it we need to call the user. save method of to
actually update this information and save it simply call the save method as well and uh refresh it now if you check
your database uh
so entry will be added right here with the username of John if you see the time stamp will take the current
time date and time so the username is successfully inserted and
uh now in the next section guys we will be tackling the messages if you type any
message on the screen so this is working for every client if you open this window in a
different client a different incognito window so this will treat it as a
different person which is logging inside your application so again it will show you this alert screen so let's suppose
if I enter a different username
uh I call this as Smith so now you can see in both the
windows it has been broadcasted that this user also know that this user has
joined the chat so now if you refresh there will be two users in the
database John Smith in the users
table so now in the next section we will be
tackling about the messages uh but before that guys we just
need to implement one other functionality so whenever someone leaves the chat we need to delete this username
from the database let's suppose uh there are two clients connected so once
someone leaves we also need to show a notification message that Smith has left the chat if I close this
window I also need to delete this username from the database as well so how we can do that it's very simple
again we will in the socket. on disconnect event right here we will
simply say if socket do username evolutes to true because we
actually added a property called as socket. username here we are checking that if
the username is already set in that case we need to remove it we will simply
again call the user model class and this contains a function delete
one and here you will be saying
username just delete that username which is present in socket
username just make this function async after this we need to globally
tell each and every client again you'll be using input output emit this time
this will be user left and we'll pass the actual username
socket. username that's all this is a logic very simple when the socket
disconnects we actually look out for if the username exist then we delete that user from the database and send out a
event back to the client user left now we need to catch this event in similarly
similar Fashion socket. on user
left and we will actually get the username and we can actually again show the same
message this time the message will be has left the
chat that's all so you will see you will get a message
for joining and if you
now if you say Smith Smith has joined the chat and
let's suppose if I close this window you will now see Smith now has left the chat
and that entry will also get deleted so now you will
see that entry will not be there it's only there once because the
for the second time we deleted it so now in the next section we'll be
tackling the messages if you type any message we need to show it on the screen so for doing it it is now you see it is
automatically uh submitting the form so we need to tackle this in the next section uh now
guys in this section we will be implementing the last functionality in the application which is the messages or
we'll be handling the attachments so for doing this uh we need to go to our client JS file and right here we need to
get references of all the elements so first is a message
form so when you submit the form you need to get the reference here whatever
ID that we have given to the form which is message form also we need to get the
message input reference here in this field we'll be entering the actual
message that needs to be sent I have given an ID to it of message and lastly
the file input so this will be the attachment we given an ID of file so
both these Dom elements both these three Dom elements and here we will be binding
message form and add event listener so when the
form submit this event handler will automatically execute e parameter will
be passed just make this function as asynchronous and you'll be preventing
the auto submission of the form by e. prevent default after that we will simply check
in the if condition that if the username do if the user doesn't enter the
username if the username doesn't contain a value then in that case we will show a
message that uh username is required to send a
message and we will not execute the application just write the return statement so the application will exit
similarly if the username doesn't enter a message or neither it's he selects a
actual attachment file input do
files dot
length comes out to be zero in that case we will say simply say to the
user you need to enter a message or selective file to
send also you'll simply return so one other scenario will be
there if the user selects both the things if they also write a message and also select the attachment
as well in both these scenarios and condition is there
so in this scenario also you'll simply say to the user that you can't select both the
things you can only send a message or a file not Mo
both you can allow the user to send both but in this application I will not so we
have added these three conditions so if the all these conditions are met in that
case this now code will be executed we will simply construct a form form data object new form data and we'll be
passing the whole form message form as an argument so this form if for this form
data to work you need to give these name parameters we have given if you see we
have given the name parameters username message file so this is very important
you need to give name parameters for form data to work after that in this TR catch block
we can actually make a fetch request to the slash upload this will be
a simple post method we'll be sending the full body as form
data so inside your try catch if any sort of error take
place so this actually uh will return either okay response so if response.
okay in that case we need to reset the input field so we simply say message
input.
value or file input. value so we are resetting that whenever form submits
successfully so now we need to write this uh backend request inside your
main.js file so just shift this code right at the
top just after here you can just see so now after the get request you can just
write app. poost SL upload and first of all we will simply
say upload do single and you can see we have given this name parameter of
file we have given this to the input element where to the attachment right here here
we simply making this route and simply allowing the user to actually upload the file if any file was selected by the
user molter will successfully upload that file in this middle we so this will be asynchronously
function this Middle where we already configured early on if you see this is coming through
sorry you need to declare it early on right here just write here declare it
now we can access this middleware we are passing this as a request upload do single
file so now we can simply get the
message we instantiate a new reference of the message class message model class
it will be imported and here we'll be sending four properties the actual username
which will be getting request. body. username the actual message request.
body. message if the message is not available in that case we will be
setting it to nothing if the user has selected a file
in that case we'll say request. file we'll use a tary operator if the file is
selected then request. file do file name we'll get the file name using this if
the file name is not selected in that case we'll say to nothing lastly the file type is the
extension so if the file is selected in that case we will get the file type using request. file do MIM
type or nothing we have getting these four
parameters now we can simply save this inside mongodb so we'll say await
message. save save the message and then again we'll be emitting globally this
event to all the clients new message we'll call this event as this and in the
payload we will be storing we will be just declaring this object message
dot user username and the actual message which
will be message do message
file message. file and uh file
type message. file type so we are sending this whole object
as a payload to the client and lastly we'll be sending a 200 status request so when
the CL it is automatically done you're sending a status of 200 which is
successful so this is our backend request now in the client GS we are getting this
response. okay to be true
so we need to catch this event that we that we are sending from index.js you
will see new message we need to catch this event and update the
UI so now to catch this again we will be using the same logic right here
s.on new message and we'll get the data object
right here you can console log it just to cross check if I refresh now and type
any message hi click on send just refresh
here so here you'll see nothing will happen if you check the console you will we get an object right here which will
have four properties a username which has sent the message which is John the message is actual High file type and
file you will actually get all this so it is saying response is not
defined uh I think in
the and the line. JS it is telling us that response is not
defined sorry I call this as it needs to go inside it sorry I just
right here we need to call this so now if you write any other
message right here refresh it just clear out the console hi
hello click on send you will get this object right here now if you want to again it will
reset if you want to select the image file you select the image click on send
now it will be a image you will see that the message will be empty now we are getting the image path the file type
which is image/png and the username so we are actually getting the actual information that we need now we just
need to update the UI and if you check in the
a table will be created of messages in the bongod DB database and we are storing all these messages in the
database so that when we refresh the page all these messages will come back
and show it in the screen so now to update the UI is very simple
uh go to your client JS in the new message
event we will simply create a new message variable
we'll create a dynamic Alli tag once again create element
Ali and we will be manipulating the inner HTML of It new message inner HTML
and we will be simply be having the strong tag and inside this we will have a span
tag so inside the span tag we will be giving a class to it of
user so here you'll be embedding the
actual username and we'll simply be saying we giving some styling right here
let me just copy paste it so you will see we have embedding the
message right here and the actual username we have
given some styling right here after you do this you need to actually add this to
the Dom so we you'll simply say messages container append child and new
message so if you just refresh now type a
message you need to enter a message of select a file
so uh nothing happens let me see what is the problem um new message in an HTML
uh I messages container message sorry I
call this message container so that was a problem so this was message
container so if I type a
message just refresh now now you will see the message will
come on the screen as well you can type any
message so you can see that so if you select image I think the image will not
come because we didn't handle the
image so the image will not display because we do need to handle a case for this we do need to actually have a if
condition right
here so you will simply have if condition
that if the data has a file attribute attached to it then in that case we need
to display image file so we'll be creating a dynamic div
element which will
have data. file type property that we have so here we'll be checking that if
the file type starts with image slash so here we simply know that
if it starts with image slash then it's a image file and for that we will be
actually be creating a image element IMG tag and image. Source will
be equal to SL upload slash followed by the actual file data.
file and then we will be adding this div to the image tag like
this so if you now check uh I think the image should show if
I go
to if I select image file
the image is not showing let me see data. file uh the error was guys the
image was not showing because we haven't added this file diff to our message
container so this is the actual problem so we do need to add this to the new
message right here that we are creating so right here we need to say new message append child and then we need to append
this child which is file div here we'll be showing our image file if the message is a image that the user is
sending so now if you navigate to your application if you try to send a
message which is a image file not a text so you can see you can test you can
send text messages and now if you want to send a image file you can actually select
to image file let me go to the downloads folder
and here if I select any jpg or file click on send and now you can see that
guys the image is sent and if I try to open this in a new
window so this is a second client which is connected this is so let's suppose if
I send a message right here you will see Smith has joined the chat if I click hi
you will see the message will be prompted you will see Smith is saying hi so if I send out image from this this
client so now you can see that the image is sent to both the clients and now you can simply chat with one other by
sending text messages or you can send out images so one other thing is that if you don't want to send image if you want
to send any other file so that the user can download it on their end so this is very easy you can just write else
condition right here you can write here if the image is not of the type uh image
then we just need to show the link to the user so that the user can download it so we can simply say we need to
create a element here a anchor element and right here we will simply say link.
HF is equal to SL upload slash followed by the data. file and we need to make it
downloadable so we will say link. download. dat. file and link. text
content and it will be shown the data do file whatever is the name of the file
and we will lastly we will be appending this file append Child Link that's all
we will add this link hyperlink to this file div and lastly we are appending it to a new message like this now if you
try to send any other file up which is not a image file let's suppose you are sending a PDF
file click on send and now you can actually see I need to send
uh I think let's suppose if I send right here this file
uh a video file uh but it is not showing let me see
what is the problem uh object is returned to us you will see that it is
file type is is saying video/ MP4 so the video is not
showing I think there is some kind of error which is
there uh link. HF data.
file let me just copy this guys and show to you
so let me just remove this so This is actually the code the link is given guys I think I made a typo mistake right here
this is the case for the image file if the image if the data type file type starts from image
slash so now if I try to do this
if I send a you will see basically now if I try to
send the image uh a video
file uh now guys the all the things are correct you will basically see we have
the if block else block there was not a problem in the code it was just internet connection problem now you can see that
I'm just running this application local h 3000 and if I try to open another incognito window Local Host
3000 you will actually see it will tell me to actually give a username and we
see Smith has joined the chat and uh if I just make it these window side by side
you can just exchange text messages if you type
hi you will basically see uh this is Local Host 3,000
sorry so if you Ty high and you will basically see it is return here you can
exchange text messages you can exchange let's suppose if you want to send a PDF file you will see the link will be there
and now the user can simply click and they can download this PDF file inside their machine
like this and if you want to send images you can even send PNG jpg image you see
the imag is reflected in both the windows so it can be multiple clients connected with each other chatting with
one other so it's a Facebook Messenger clone guys you can see how this if I
left left you'll basically see uh Smith has left the chat again if I join it you
will see it will detect the local uh local storage Smith has joined the chat
and if if I leave it from here Gotham has left the chat and again if I
join so Gotham has joined the chat so you will basically see it's a mini Facebook Messenger clone and also if I
refresh the application if I refresh the chat all the previous messages will be staying right here how I how we are
doing it so just go to your home route where you are actually loading inside
your main index. J is in the server site code so here we will simply we need to
uh we are simply finding all the messages you will see that message. find so this method find will actually
return all the messages previous messages which are there and we will be actually be rendering it in the EGS
template we will be sending this variable messages which will be an array here which will contain an array of
messages and now in the index.js template you will see we are storing all these PDF image files right here in the
uploads directory and right inside your views folder we will simply make a
simple Loop right here if you see in this Loop right here we are
actually using the for each Loop for each message we are displaying the username we are displaying the actual
message and we are again having this if condition If the message is of the Type image then we are simply showing it in
the if condition we are showing this image tag if the image If the message is not a image then we are showing the link
right here very simple message. file so downloadable link so when you reload the
application let's suppose if you close it want to reload once again the previous messages will show so you will
see that all the previous messages are showing right here so this chat can support multiple clients multiple users
can chat with one another simultaneously using this Facebook Messenger clone if you need the full source code guys the
link is given in the description you can directly purchase the full source code with fall documentation and support from
me and uh the link is given you can directly go to procore.com and you will actually get the zip file from Google
Drive after you purchase the full source code and please hit that like button guys subscribe the channel as well if
you like this video and I will be seeing you guys in the next video