2. Setup Code
On this page, we will start coding our Node.js chat app.
At the end of the previous page, we installed Socket.IO and Express as part of our project. Socket.IO enables you to communicate between the browser and the server at top speed. Express is a framework that provides a set of features for Node.js applications. Both of these are very useful.
First, inside your chat-app folder, create a new folder named public. This new folder is where we will keep all our files for the users. Inside the public folder create an empty file named index.html. This is the main HTML file that will be run at the start. So far, your file structure should look like this.
Let's focus on our server-side code. We want to import Socket.IO and Express. Type the following in your server.js file.
When a user connects to our application, the server needs to supply them with main HTML page. The code below, tells the server where this HTML file is.
Finally, we need to set a port for the server. This is the place where the server will be waiting for users to connect. We will set the port to 5000 and make it print a message.
Now we will focus on our client-side code. Write the following HTML code inside index.html.
Go to the Command Terminal and make sure the its current directory is your chap_app folder. If not, change the current directory.
Now type the following into the terminal
It should then print server listening. Now go to your web browser and visit localhost:5000, it should take you to the port we set up earlier. If everything works as planned, you should see this.
You have officially built your first Node.js application.
Because we are currently connecting through localhost, no one else can access this website. We will use localhost for testing and later we will release our application online.