In this tutorial we’ll see the basics of creating a Node.js project with two of its most popular modules: Express.js and Socket.IO. We’ll build a simple chatroom from scratch, like those from the early Internet days :P.
We are going to be building the project from scratch, so the only requirement is that you install, of course, node and npm (if not included with node). Also, I assume you know JavaScript. If you don’t, I totally recommend JavaScript’s track at Codecademy.
Creating a Project
Create the folder where we’ll have our project, we’ll be working from here from now on.
In Node, we don’t really create a project with a specific folder structure, but create an app file instead; that is, the file that will be executed as the node application. You may name the file as you want; in most of the projects I’ve seen it named either app.js or server.js. Since we’ll be building a web server, let’s go with server.js.
Let’s make sure our node installation works properly. Put the following in server.js:
Now, run your app. From a terminal window, execute:
You should see the output:
Ok, good to go! Now, create a file called package.json.This file serves the purpose of packaging your node project. Here you can specify the project name, author(s) info, dependency modules, node version, etc. There’s an excellent cheat sheet that you can use to package your own project.
For this project, the only info that you need in your package.json file is the following:
You can put as much info as you like; the more info you put, the more info you are giving others about your app. The dependencies object is used by npm to download any necessary external modules for your app. Let’s go briefly through each one:
Express: a web framework for node. It is one of the most used modules in node.js; it takes care of a lot of boilerplate code to build a web app. If you are using views in your project, it expects you to use a template engine. By default, it expects Jade to be used.
Jade: a template engine for node. If you know HTML, you’ll love Jade. Briefly go through the docs and you’ll see what I mean.
Socket.IO: a module that makes real-time apps possible. We’ll go into more detail later in this tutorial.
Underscore: a utility module that has many common operations that you would normally use in other dynamic languages like Groovy or Ruby.
Body Parser**: **middleware parsing utility for node. We’ll use this to let the server parse JSON requestsNow that we’ve included our dependencies for the project, let’s tell npm to install the binaries:
Npm will automatically read the package.json file and download the dependencies noted in it. The output should be similar to the following:
You should now have a folder named node_modules. The folder contains all the necessary files and binaries to run your project. This means that now this folder is truly the root folder of your project.
HTTP Server Setup
To set up the HTTP server using Express, we also need the http module included with node. You can go through the node documentation to see other modules included with it. Let’s change the contents of server.js as follows:
NOTE: I’ll comment where necessary; otherwise, it should be self-explanatory.
Start the server:
You should see the message:
If you go to that address in a browser, you should see a message as follows:
Awesome! We have an HTTP server up and running. Granted, it doesn’t do much but if you have worked with other web frameworks, you have to admit that it was very easy to set up an HTTP server. If you wanted to use an HTTPS server instead, instead of using the http module you would use the https module instead. Yup, is that easy.
Building a Jade View
This is a two-step process. First we have to tell our server that we are using Jade as our template engine. Then, we’ll create the view of our chatroom.
Add folders to our project where we’ll have all static content (css, client javascript), and one folder with our jade templates, or views. Add the following folder structure to the project:
Let the server know about this folder. Stop the server if you haven’t already done so and modify server.js:
NOTE: Changes in bold.
Great! Now our server is ready to display views. The only thing missing is an actual view! Under the views folder, create a file named index.jade. This is the view we are telling the server to render when accessing http://localhost:8080. At this point you should probably take a quick look at the Jade documentation but if you don’t feel like it, don’t worry, I’ll create a simple document and the Jade syntax should be self-explanatory. The contents of index.jade should be the following:
I’d like to point out that Jade is awesome, I think the documents look way more elegant like this as opposed to simple HTML. Anyhow, we also need to create a stylesheet for the classes we assigned to some of the elements. It should be named style.css under the folder public/css/ with the following:
NOTE: If you decide to name the file other than style.css just make sure you also change it in index.jade.
We have our view! Start (or restart) the server, open the browser and go to http://localhost:8080. You should now see an awesome chatroom that doesn’t do anything (yet!) like the one in the picture:
Web Services with Express
Express is great for creating RESTful web services. From the frameworks I’ve worked with, it has to be one of the easiest, if not the easiest, to build them with. If you take a look at server.js you’ll notice we have the following function to render our view:
We could easily change a function like the following:
And that would create a GET service at “http://localhost:8080/” that returns a JSON object. Awesome! Isn’t it? Let’s add a POST method to our server.js to send a chat message. We will also begin using Underscore:
NOTE: Changes in bold.
Let’s test our POST method, (re)start the server and call the method at http://localhost:8080/message. I’m using curl as my REST client, but you can choose whichever you want.
Let’s test a bad request.
This is as far as we’ll go with RESTful services in this tutorial, but feel free to browse through the Express documentation and build more methods or add options to our POST method.
Making real-time apps with Socket.IO
So far we have a web server that receives incoming messages that does nothing with them, and a view that can’t even send a message. I think that now it’s a good time to make this a real-time app. Let’s talk a little bit about Socket.IO first.
Socket.IO is a module that aims at making real-time apps possible. Long story short, it consists of a server that receives and emits events to all the clients, or just a set of clients, that connect to it. Here’s a list of browser and transport support for it. There are many websites that use Socket.IO, however, an excellent implementation of it is Trello. Fog Creek Software, its creator, have an excellent post on the website’s tech stack, including comments on their implementation of Socket.IO. It is definitely worth a read.
We are going to set up our socket server with our web server, but if you are considering building a huge website you should definitely implement your socket.IO server as a dedicated service instead of mixing it with your web server. Modify the header of server.js with the following:
NOTE: Changes in bold.
Yup, we now have a socket.IO server up and running at the same location as our web server (http://localhost:8080). Let’s test it, shall we? For development purposes, socket.IO serves its client library at /socket.io/socket.io.js. Let’s also go ahead and create a JavaScript file that will be used in our client. Name it index.js (or whatever you like, just make sure it’s called the same in your index.jade file) and add it to our static location of JavaScript files, public/js/. Finally, we’ll use jQuery for our client code, so we’ll use it with a CDN (this example works with version 1.11). Modify the head tag of index.jade so it includes all JavaScript files, socket.io.js, jquery-1.11.0.min.js and index.js:
NOTE: Changes in bold.
Let’s put the following in index.js:
NOTE: I’ll comment where necessary; otherwise, it should be self-explanatory. Also, I’m not going to explain jQuery, you can go to Codecademy for that. They’ve got excellent tutorials.
Let’s test it! (Re)start the server, as soon as you start the server you should see an info message from the socket.IO server:
Open the browser and go to http://localhost:8080. Take a look at the browser console and you should see the log along with a session ID as follows:
Woohoo! We now have a socket.IO server along out web server and successfully connected a client to it. We can now finish our chatroom!
A Chatroom
Let’s use what we just did to finish our chatroom. We are going to be working with the following events between our client and server:
When a new user connects to our server, he will emit an event called newUser and the server will emit an event called newConnection with a list of all participants to all connected clients
When a user changes his name, he will emit an event called nameChange and the server will emit an event called nameChanged to all participants with the id and new name of the user who emitted the original message
When a client disconnects from the server, an event called disconnect is automatically captured by the server. It will then emit an event to all participants with the id of the client that disconnected
When a client sends a message through our POST method, the server will emit an event called incomingMessage which will send the sender’s name and the message to all clients to show on their viewsLet’s add all this fancy stuff to our server. This is the final version of server.js:
NOTE: Changes in bold.
I think the code and the comments are self-explanatory. If not, let me know in the comments section to update it accordingly.
Let’s finish this chatroom by extending the index.js file with the events we just defined.
NOTE: Changes in bold.
Aaaaaand, that’s it! (Re)start the server and see our chatroom in action!
Let’s open a browser to http://localhost:8080. You should see the following:
Now, open another tab or window at the same address:
You should see the list of participants on both sessions. Now change the name of one of the users:
All sessions should reflect the change:
Send a message from one of the sessions:
Check the other session to see the message that was sent:
Finally, send a message back to the other session:
Your super awesome chatroom is now complete! Note that this is a very basic implementation of different node modules, and also know that this chatroom is vulnerable to XSS and you should at the very least add an HTML sanitizer if you intend to use it for a real-world application.
What I would like now is for you to be creative and add events, styles, and cool functionalities to the chatroom. Share them all in the comments section or let everyone know what you thought of this tutorial!
Thanks for reading this far, I put a lot of effort into making this tutorial. If you liked it, I would really appreciate it if you could help spread the word by sharing this post.