Node in Express and npm which is the. node package manager and we’re gonna go. ahead and use NPM to initialize a. package.json file by doing NPM in it and. this of course is in the root not in the. public directory so let’s just go. through this package name version. description we’ll say real time chat app. with rooms and entry point I’m going to. use server Jas and author of course you. can use your own name and then license. I’ll do MIT so that creates a package. jason which is just basically a manifest. with some information any dependencies. that we install and so. so I’m gonna go ahead and install what. we need for this project so NPM install. Express which is our web framework we. need socket IO which is a framework for. dealing with web sockets and also moment. which is moment J s and it’s used to. format dates and times so those are the.
Only dependencies that we need in terms. of regular dependencies I do want to. install node Mon as a dev dependency so. let’s say npm install upper case D for. dev dependency and then node lon. just so we don’t have to keep Reese. restarting the server every time we make. a change. it’ll constantly watch it alright and. then I just want to create a couple. scripts so we don’t need this test. script so we’ll create a start and all. this is gonna do is call node and then. the file name the main file which is. server jsr just server and then we’ll. have a dev script that will call node. lon and then the file name which is. server alright so that’s all we have to. do in the package Jason so we can go. ahead and close that up so let’s create. our server J s okay so this is basically. this is our backend this is the entry.
Point to everything and we’re gonna. bring in Express basically I’m just. going to create a very simple just. regular Express server first and then. we’ll move on to implementing socket IO. so let’s bring in Express and let’s. initialize a variable called app and set. that to Express and then on that app. variable on this object we can call. listen to run a server and this takes in. a port number so let’s create a variable. called port and I’m gonna use 3000 but. I’m gonna say also say or process dot e. NV dot port so it’s going to look to see. if we have an environment variable named. port and use that if not then use 3000. and we just plug that in here and then. we can optionally have an arrow function. and we’ll just do a console log here. backticks and say server running on port. and then use our variable syntax to put.
In that port number so just this excuse. me just this should actually run by. doing npm run dev because we created. that dev script and we get server. running on 3000 now I want to have this. public folder set as our static folder. so that we can access these HTML files. and access our frontend so the way that. we’re going to do that is by setting. here let’s say set static folder and. with Express we just do app dot use. Express static and then the name of the. folder that we want and I’m just going. to use the help of the path module which. is a node.js core module so I’m going to. bring that in so we’re going to require. path and then inside here we can simply. say path dot join and we want to join. the current directory so during the. underscore or double underscore dur name. and then the public folder and that sets.
All bring in the. HTTP module or package or whatever you. want to call it and this actually is. used by express under the hood so. there’s a method called create server. that express actually uses but we want. to access it directly because we need to. in order to use socket IO so what we’ll. do is create a server variable and set. this to HTTP and then we want the create. server method and we can actually pass. in our Express app and then instead of. doing app dot down here app dot listen. we’re gonna do server dot listen and it. should still work we’ll just stop the. server with control C and run it again. and you can see it still runs alright. now to use socket dot IO we have to. first bring it in so we’re gonna call. this socket IO set this to require. socket dot IO and we want to initialize. a variable called IO and set that to.
Socket IO and then just just simply pass. in our server ok and that way we can now. let’s see let’s actually go under this. and now we can say run when a client. connects so we can take that IO variable. or IO object and say dot on which is. gonna listen for some kind of event and. we’re gonna listen for our connection. and then this will take in an arrow. function with socket as parameter ok and. I’m just gonna for now just say. console.log and let’s say new WebSockets. connection. so we’ll save that now whenever a client. connects it should go ahead and. console.log this so we don’t have. anything set up on our front end to be. able to do that so let’s jump into chat. HTML and now that we have socket IO set. up on our server we can use the front. end library. year so in our chat HTML we’re gonna add. another script tag with a source and we.
Or emit messages or I should say events. back and forth that’s really how this. works it’s a it’s an open bidirectional. communication think of it as an open. door between the client and the server. and we just can it we can emit events. back and forth so I want to be able to. emit a message to our client from our. server so in our server Jas and make. sure we’re in the connection here we’re. going to emit so socket dot he met and. we’ll call this message you could call. it can emit whatever you want call it. whatever you want and then also send. whatever data you want in this case I’m. just gonna send a string that says. welcome to chat chord okay. now I’m gonna save this and the way that. we basically catch this on the client. side is in our main J s we can now take. that socket variable and say socket dot. on just like we did on the server and.
Say on message so whenever we get this. message event and we get a message we. get a function here with a message. parameter because on our server side we. sent this right here which is going to. be this message in fact I’ll console.log. this message and if I save that and we. go back and then I open up my client. side console and reload we get welcome. to chat cord okay because that fires off. right away as soon as we’re connected it. logs here on the server and then it. emits the message which we then catch. here and then log now we’re going to be. sending a lot of different types of. messages we have our welcome so we. emitted this welcome message we’re going. to send of course when we type in a. message also when someone connects and. disconnects I want to have a message so. I’m gonna go right here and let’s say.
Broadcasts when a user connects so for. this we’re actually going to do socket. and instead of just dot emit we’re gonna. say broadcast e dot e met now the. difference between socket dot e MIT and. broadcasting MIT this will actually emit. to everybody except the user that’s. connecting we don’t need to notify the. user that’s connecting that they’re. connecting this will emit to just the. single user or a single client that’s. connecting and then if you want to. broadcast to everybody like you would. when we send a message you would do IO. dot emit ok so there’s basically three. ways to do it this is to the the client. the single client this is to all of the. clients except the client that’s. connecting this is to all the clients in. general alright so we want a broadcast. when a user connects so this is going to.
Be message and the message is going to. be a user has joined the chat and later. on we’ll have actual user names now at. the same time when there’s a. can act so down here let’s say this runs. when client disconnects and then we just. want to say socket dot on disconnect I. know it’s a little weird that like this. is inside of the connection but it has. to be you don’t want to have this. outside of it. so on disconnect then we’re gonna have a. function I’m just going to use an arrow. function and I want to then emit to. everyone that the user has left the chat. so we’re gonna do io dot emit meaning. let everyone know and we want to emit. message and we’ll say a user has left. the chat all right so this here let’s. just say welcome current user and we. don’t actually need this console.log. anymore. okay so with all of these we’re emitting.
Message which we’re catching here so it. should log all this stuff so I’m gonna. go ahead and reload here and I’m gonna. take localhost 3000 and go to a new tab. and this really doesn’t matter this is. just gonna bring us to chat HTML so. we’ll go ahead and join and then over. here in the console you’ll see a user. has joined the chat if I either leave. room which will just bring me back to. the form you know the join or close the. tab you’ll see now a user has left the. chat so those broadcasts are working. correctly now the next thing I want to. do is implement this messaging so if we. type something in here and send we want. to we want to then emit that to the. server and then have it sent back so we. can put it into the Dom so let’s go to. our main j/s and we need to somehow. access that form. so let’s create a variable called chat.
Form and bring in that Dom element so. document dot get element by ID and that. form has an ID of chat form so if we. look at chat HTML where is it right here. form ID chat form so we want to. basically create an event listener for. the submission of that form so we’ll say. message submit and we’ll take chat form. and add an event listener we want to. listen for a submit and then that’s. going to take in and function I’m going. to use an arrow function and we want to. pass in the event parameter here because. when you submit a form it automatically. just submits to a file and we don’t we. want to stop that from happening so we. can use a dot prevent default which will. prevent the default behavior and then we. need to get the text input and we could. do that a few ways we could grab it from. the Dom but I think a neater way to do.
It is to let’s just call this message we. can take a dot target okay so that will. give us the current element and we have. access to elements and then we want msg. so basically we’re getting it by its ID. which if we look at chat HTML has this. idea of msg so we’re getting that but we. do want the value so we have to do dot. value and then what we’ll do is console. log msg so now when we submit the form. it should get the message from the text. input and then just log it on the client. side we’re not yet dealing with you know. submitting it to the server or anything. but let’s just try that out so reload. type something in send and it logs now. instead of console logging we don’t want. to do that we want to sock it dot emit. okay so we’re gonna emit and we’re gonna. give this a name of chat message. and we’re gonna send that message as the.
Payload. okay so I’ll put a comment here so we’re. emit emitting a message to the server. see here we’ll just say get message text. all right so now on the server side. let’s go to the server j s and we. emitted chat message so now we basically. have to catch that so within this. connection here let’s say listen for. chat message and the way we do that is. with socket dot on so on chat message. then we’re going to have a function an. arrow function with message as parameter. that we can have access to and I’ll. console.log that on the server side so. now when I send a message it should log. down here on the server right so let’s. reload this and just type something in. and send and if we look down in vs code. and the terminal it’s logging on the. server now what we want to do is is emit. this back to the client right so we want.
Message. server and then down here let’s create. let’s say output message to Dom so. function output message which takes in a. message now we have to do a little bit. of Dom manipulation here so I’m going to. create a div and we’ll set this to. document dot create element which does. just that we’re going to create a div we. want to add a class to it because if we. look at the format of the messages so we. have a wrapper or is it of chat messages. and then each message has a div with the. class of message and then inside that we. have two paragraphs for the meta and the. text so we want to add this message. class so let’s do that let’s take the. div and say class list which will give. us all the classes but we want to add on. to that the class of message and then we. want to take that div and we want to set. the inner HTML equal to some backticks.
And if we look in the HTML again the two. paragraphs we can just copy this paste. that in there now we don’t have access. to a name or time or anything but. remember we do have the message so we. can replace that with message and then. the last thing we need to do since we. already have everything created is put. it into the Dom so we’ll say document. dot get element by D and let’s grab the. or actually we don’t have an ID do we we. want basically we want to take this chap. messages right here which is a class so. let’s actually use. query selector and we want to select the. class of chat messages which is the. container and then we want to append. child and append the div okay so. whenever we create a message it should. add a new div to this chat messages so. let’s try this out it should work so. I’ll reload and we automatically we get.
Welcome to chat chord because that’s. sent from the server right away when we. join right so up here we catch it we’re. logging it and then we’re setting it to. this output message which then puts it. into the Dom now at the same time when a. user joins or leaves or we send a. message it all gets emitted as message. so all of these are getting caught right. here right and it’s gonna hopefully it’s. gonna run this so if I put something in. here like hello and send there we go now. it’s always gonna say Brad this and the. time this is hardcoded right now but. we’re gonna fix that in a little bit if. I open up a new tab and join we should. see a user joined okay so if I go over. here we see a user has joined the chat. if I leave a user has left now at the. moment it doesn’t matter which room I. join even if I join PHP it’s still gonna.
We’re ready to start doing like users. and in rooms because right now we have. the just the message stuff shut setup. actually you know what let’s format the. message cuz right now it’s just a string. it’s always just a single string I want. it to be an object with a time. ultimately we want the user and stuff. like that so let’s go to server J s and. everywhere where we send a string here I. want to wrap it in a format message. function so I’m going to create in the. root here a folder called utils and in. utils we’re gonna create let’s call this. message or messages j s and in this. messages dot J ass I’m just going to. create a function called format message. oops format message as a function and. it’s going to take in two things a. username and the text message and from. that we want to return an object with.
The username so that’s just like doing. this with es6 we can just put in just. the username tax same thing and then I. also want to add the time which I’m. gonna get from that moment J s library. that we installed so let’s say Const. moment equals require moment and this is. really easy to work with if we want. today’s or right now like this date and. time right now we can just use moment. dot format although that’s not going to. look too good so we can actually put. some stuff in here all I want is the. time so our : minutes and then a.m. or. p.m. and that’s it we just need to. export this so module dot exports equals. format message and then we can bring. that into our server J ass and use it so. up here it’s a Const format message. equals require. we want to go to utils slash messages. now everywhere that we sent that we send.
A message we actually want to instead of. just sending a string we want to send. format message with a username now this. stuff here like the welcome let’s just. make sure we add our ending parenthesis. everything that is like a welcome or. user join the chat that’s going to be. from the chat cord bot or whatever you. want to call it you could call it admin. or whatever and since I’m going to use. this in so many places I’m going to. actually create a variable called bot. name and we’ll put that right up here. Const bot name equals Jack cord bot so. we’re passing in the user name in the. message again we’re calling this. function username and mold I should say. text the whole thing is the message. that’s just the text okay so hopefully. that makes sense now I’m going to just. copy this and we want to do the same.
Thing here so let’s see bot name and. then add the closing parenthesis and. then we don’t want to let’s see let’s do. this disconnect. okay so bought name close that and then. this here where we’re actually taking. the message from a user we’re not going. to be using bought name so what I’ll do. is for now let’s wrap that for now let’s. just say user that’s going to be. replaced later on so if we save this. let’s go back and reload now notice what. we’re getting back from the server now. an object with username which is Jack. korte bought in this case text and time. okay now in here we’re now seeing just. an object because it’s this is no longer. just a string it’s an object so these. two we can ignore in fact we can get rid. of those if we go to our template right. here just get rid of these two hard. coded messages so that it’s just an.
Empty div an empty chat messages div. that way we don’t have to deal with. those two phony messages so in order for. this to show the text we need to go to. our main J s and go down to the output. message and this is now an object right. it’s no longer a string so we want the. text property from that also we can get. the time now so we can set this to. message dot time okay the user actually. you know we have the user that’s right. so we’ll set this to message dot user is. it username let’s see yeah username all. right so let’s save that and go back and. reload and there we go so chat cord. bought 333 p.m. which is the correct. time and the message text and if I say. hello of course right now it just says. user because we don’t have that. functionality yet but if I go to you. know different. here room doesn’t matter yet but if I go.
Back over we’ll see from the chat cord. bought a user has joined the chat. alright awesome so now we want to start. to implement users and rooms so the way. that this is going to work if I leave. the room and I type in something here. and join notice that we have the. username up we have some query strings. with the username and the room so that’s. ultimately where this is coming from and. we want to grab these somehow now. there’s a library called Q s or query. string that we can use to grab these. values so let’s close that up and let’s. search for Q s CDN so this link right. here I’m gonna grab the minified version. so just copy script tag and we want to. put that in our chat HTML right above. our socket IO library script so now we. have access to this query string library. and the way that we can get those values.
Have access to these. so now let’s emit an event to the server. with these two things in it so instead. of console logging here actually let’s. just get rid of that we want to go under. the socket and let’s say join chatroom. so go ahead and Annie MIT an event. called join room and we’ll go ahead and. send an object with the username and the. room now we can catch this on the server. side so let’s go to to our server j/s. and we’ll just do just go right to the. top of that where this connection is. let’s see yeah so basically we have to. go right here and say socket dot on join. room. let’s see join room and then that takes. in an object with username and ROM and. this is going to be an arrow function. now since we’re using rooms from this. point on this welcome and stuff like. that the welcome in this broadcast is.
Actually going to go inside the join. room so we’re gonna go ahead and just. cut that yeah cut that and paste that in. here I actually want the disconnect at. the end so I’m gonna put that under this. chat message. okay now so we’re welcoming the user to. the room we need to join the room. because right now we haven’t done that. yet we’re just responding to this event. so we need to actually create a user so. what we’ll do here is actually before we. do anything let’s create a new file in. utils called users dot J s and anything. to do with users will go in here so join. when they leave if we want to get all. the users in a room stuff like that so. we’ll have our state which will just be. an array and obviously you could connect. up a database if you wanted to but we’re. just keep basically keeping everything. in memory so join user to chat so let’s.
Say function user join which is. basically just going to add a user to. the array and return it so in here it’s. going to have an ID every user needs an. unique ID a username and a room so we. want to create user from the stuff. that’s passed in so an object of ID. username and room and then we want to. add to the array so we’ll take the users. array and push onto it that user okay. and then ultimately return that user now. at the same time I’m going to create. another function to get the current user. so let’s create a function called get. current user and get the user by its ID. and we’re just returning the array and. we’ll use the find method which is a. high order array method takes in a. narrow function so for each user we’re. going to pick out the user where the ID. is equal to the ID that’s passed in here.
Now just like we did above we want to do. I Oh dot and then to and then the room. dot emits so it’ll be user dot room or. else we’ll just omit to every room and. now we can replace this with user dot. username in the message so now if we go. back and reload and I try to send a. message here now it gives me my name. right here alright so messages are. nicely formatted with the name the time. and. next and it’s only being sent to this. room alright now we want to do the same. with like when the user leaves the chat. because right now it’s just gonna say a. user has left the chat I don’t know why. I keep clicking over there. so in our users j/s we’re gonna have a. couple more a couple more functions so. let’s do user leaves chat so function. function user leave we need the ID of. the user and basically we need to remove.
The user from the array so I’m gonna. just there’s a lot of ways you could do. this but we’re gonna set an index and. use users which is the array dot find. index and we want to say for each user. we want to find where the user dot ID is. equal to the ID that’s passed in that’ll. give us the index then we want to check. to see if the index is not equal to. negative one because the way this works. is if it finds it it returns it if not. it returns a negative one so if not. index then we want to return the users. array without that user and we can do. that by using splice so we’re gonna. splice it out by the index and we’re. splicing one we’re taking out one and. returning it okay so that’s user leave. and then the last function is going to. be to get. rum users so let’s say function get from. users and obviously we need the room and.
We can this is pretty simple we can just. use filter so we can say for the users. array we want to filter through and we. want to say for each user we want to. return only if the user rum is equal to. the room that’s passed in all right and. then we just need to export those so. user leave user leave and get rum users. and then bring those into server J ass. up here alright cool so let’s see in the. disconnect right here so when we. disconnect we want to run that users. leave right so let’s set and we need to. know which users are left so let’s set. user to user leave and pass in the. socket ID to get that user and then. check for the user and if that user. exists then we want to do this so we can. actually just move this up into here. except we want to do I Oh dot to the. user dot room and we want to omit and.
Then we want to say the users actual. name here so let’s turn these into. backticks and. let’s say use our dot username has left. the chat all right now that should work. I mean we can test that out real quick. so if I open up another tab okay. join so we should see over here John is. join the chat and if I leave. oops that didn’t work leave okay so it’s. not doing left the chat so I must have. messed something up here so disconnect. con Ceaser user leave IO dot to the user. room were emitting a message formatting. it so this didn’t even let’s see I mess. something up here user leave user leave. ID. users find index the user ID is equal to. ID the index if it’s not equal to. negative one then we’re gonna owe so. instead of returning the entire array we. just want to return the user so we need. to just put in the zero index all right.
So let’s actually try that again so you. know what’s a second John has joined the. chat. let’s leave John has left the jack. alright so cool so now we want to work. on this stuff over here the sidebar we. need this this info right so in server. j/s we have our connection we have our. join rum. let’s go to the bottom after the. broadcasts where someone has joined the. chat let’s send users and rum info so by. to do this we’ll do I owe dot to the. user dot rum dot amit and we’re gonna. emit will call this room users okay and. then what we want to send is an object. with the rum so you use our dot room and. we also want to send all the users in. the room so remember that get user what. does it get rum users and then just pass. in user dot room so that will send it. all we also want to send it when they. disconnect because there’s going to be a.
I leave the room and let’s say Jack. joins Python our PHP now Brad isn’t in. here anymore because we’re not in the. same room and that doesn’t show up over. here perfect so this is working really. good so I think that that should do it. now of course you could add on to this. in fact I would encourage that if you. want to integrate MongoDB or some kind. of you know SQL database or whatever and. store the users and basically have them. log in to join the chat you could do. that I might actually do something with. this at a database maybe integrate. electron and make it into a desktop app. so yeah so expect to see something added. on to this application but that’s it. guys thank you so much for watching and. I hope everybody is is keeping safe and. not going nuts I know this is a crazy. time I just wanted to create some kind.