Setting up Nodejs and Socket.io for the first time

Setting up Nodejs and Socket.io for the first time

We pretty much know how websites work already, the front end being what we see and the back end handling all the background stuff we don't get to see in action.

NodeJs is an open-source, cross-platform javascript runtime environment that enables running web applications outside the browser. Nodejs has become the favourite choice among the back-end development community and has pretty much taken the title from PHP.

Socket.io is used to communicate in a swift manner events that are happening in the server and the client by enabling low-latency, two-way communication.

Okay yeah yeah, can we get to the coding part? My fingers are aching. Don't worry, and I've got you.

Setting up NodeJs

In this article, I'm going to assume you don't have nodejs already for clarity. Installing and setting up nodeJs is a pretty straightforward process. Head over to the official Nodejs website to download the latest version.

Once the download is complete, it should only cost you about 27MB, so it's a piece of cake. Proceed to install, follow all the on-screen instructions, and complete the installation.

After setting nodejs up, let's move on to some more interesting aspects of this setup. Installing dependencies.

NPM

Understand that Nodejs isn't the programming language or framework we mentioned earlier. It's a run-time environment for all other Javascript frameworks, codes, programs, and more to run outside the client browser. To make use of this wide library of tools, Nodejs grants us access. We have to make use of the node package manager.

ExpressJs

To install express, open up your command line and run the following command on your machine. I personally love to use git bash, but you can use windows cmd if you so wish.

Run the following commands mkdir myapp, hit enter, then run cd my app. You're basically telling your PC to make a directory for your app, and then you use the second command to change the directory.

Now that you're in the myapp director, it's time to run some npm. Run npm init this command will initialize the project and ask you a bunch of questions.

Ensure you click enter as the question comes up, and you should have a result like the one above. Note that you'll have to fill in some information manually, like the test command and the author. You can skip the description and git repository by clicking enter.

Let's install some express and socket.io next! To install express and socket.io, run this command.

npm install socket.io express --save

You see this result, which means the following dependencies have been installed on your project, stored in the package.json file.

Let's make sure it works!

For us to actually confirm if your dependencies are installed successfully, all you have to do is open vs code and visit the package.json file, and you should see express and socket.io listed under dependencies.

Now that we have all the dependencies for our project, we have to test them.

Testing Express and Socket.io

Head on to vs code, which is what I'm using. You can use whatever you're comfortable with and create a server.js file. In our file, go ahead and place this code there:

var express = require('express'),
    app = express(),
    http = require('http'),
    socketIO = require('socket.io'),
    server, io;

app.get('/', function (req, res) {
res.sendFile(__dirname + '/index.html');
});

server = http.Server(app);
server.listen(5000);

io = socketIO(server);

io.on('connection', function (socket) {
  socket.emit('greeting-from-server', {
      greeting: 'Hello Client'
  });
  socket.on('greeting-from-client', function (message) {
    console.log(message);
  });
});

This code creates an express app, starts the socket.io server, and registers where the result will be showing; in our code, it'll be sending the response over to index.html

Time to create the index.html file over on vs code just before we run our little program here. Once that's done, paste this code on there.

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script src="/socket.io/socket.io.js"></script>
<script>
            var socket = io('http://localhost:5000');
            socket.on('greeting-from-server', function (message) {
                document.body.appendChild(
                    document.createTextNode(message.greeting)
                );
                socket.emit('greeting-from-client', {
                    greeting: 'Hello Server'
                });
            });
</script>
</body>
</html>

The HTML file contains some very important pieces of code. The declaration of the socket variable will open a connection between the browser and the server, essentially calling the method that we added in server.js

Time to run the program, simply run node server.js in your console, and the server should start kicking; visit localhost:5000 in your browser, and you should see the magic.

Your browser should display "hello client" on the browser.

You should also see a "hello server" message from the console. This means that your express and socket.io are properly connected.

Conclusion

With that, we've properly connected our express.js with socket.io for the first time. If you want to continue your learning journey with express+socket.io, take a look at this doc that explains how to build a chat app, and follow me on Twitter for any questions you might have.