A think what I wanted to create at the beginning with NodeJS was a Chat application. This is not really complicated but when you start with NodeJS you feel a bit lost with all the technologies around this. With this tutorial the idea is to give a short way to get a chat app working on NodeJS. I'll not explain all the theory around what we will do then maybe if you're not familiarised with NodeJS you will feel a bit a lost, but not be afraid and just go ahead and everything should be fine at the end of this tutorial.
This tutorial does not speak about permanent data, that is mean if you quit the app and go back you will loose all the messages.
Enjoy and have a fun!

Prerequisites

  • NodeJS version 0.12.x
  • Express version 4.x.x
  • Express-generator version 4.x.x
  • Not be afraid about command-line tool even for Windows user
  • Javascript / html skills

Prerequisites installation

1. NodeJS and npm

The NodeJS installation will be depending of your platform, then it's a bit complicated to explain all different installations here and is not the focus of this topic. You will find all documentation needed around the WEB but mainly on the NodeJS official website.
When NodeJS will be installed to your computer you can go ahead with next chapter.

2. Express and Express-generator

NodeJS is delivered with a good package manager call npm. This tool allow you to install simply some node-modules without any effort as Express.

Express is a WEB framework for NodeJS that provides a set of features for WEB and mobile applications that simplify the NodeJS applications development. Have a look at the official website for more information.

The installation has to be on the global system that is to say it will depending of your platform. With Windows usually user is also administrator then nothing special is needed. If you are running OS X or GNU/Linux user is just a user, then you will need the access to admin account or the sudo command with the root password. For my case I did the installation on a Linux Debian Server.

Debian linux installation

Open your favorite console

su -  
root password  
npm install express -g  
npm install express-generator -g  
exit  

OS X and Linux distribution that use SUDO command

Open your favorite console

sudo npm install express -g  
root password  
npm install express-generator -g  
root password  

Windows installation

Open the command line tool "cmd"

npm install express -g  
npm install express-generator -g  

And that's it!

Create the new express chat project

From now all the dependencies are installed then we can follow by create a new express project with the express-generator.
In your favorite console or inside the command prompt of Windows run this following command

express -e mychat-app  
cd mychat-app  
npm install  

So here what we did? Basically we created a new express project call mychat-app in the folder that you are with your console.
The -e option is to use the EJS tempting engine in order of Jade that I completely dislike and is the default with the express-generator! If you want to know more about javascript engine there is a good overview on this address Comparing javascript templating engines
With the command cd we have moved inside the new project folder.
With the command npm install we have installed all the node-modules needed by express that are referenced inside the file package.json of our project.

From this time we already have a functional express application that you can try with the following command npm start and should get something like:

If you open your favorite browser and open this URL http://localhost:3000 you should see your application that is just saying:

Great! First step is done! To kill your app just use the CTRL C combo on your keyboard with the focus on the console application.

Start coding the chat app

Finally here we are!

The first thing that we will need to create a chat application is something to listen all the client connections on our server and when one of them are sending a new message in order to the server can send this message for all other clients. This something is call Socket.io and to install it in our project nothing than simpler to use npm:

npm install socket.io -s  

This command will install socket.io node-module to our mychat-app project.
From now we will need to edit few files inside our project to bind our socket.io server on our mychat-app, and change the html template to add a field to send a new message and an area to see all the messages send by all users. To do that you will need a text-editor and even a text-editor that supports the color code syntaxes. If you have no idea what to use I can recommend to you to use brackets.io. It's a simple Open Source code editor that is not bad for starting. Personally I use Sublime Text 3 that is not free but really powerful.

Binding socket.io to our app

First edit the file app.js and add this app.io = require('socket.io')(); like this:

...
var app = express();  
// call socket.io to the app
app.io = require('socket.io')();

// view engine setup
app.set('views', path.join(__dirname, 'views'));  
...

This code will call the socket.io node module on our app and directly attach it to the express app that is declared just before.

Now edit the file bin\www and add this app.io.attach(server); like this:

...
/**
 * Create HTTP server.
 */

var server = http.createServer(app);

/**
 * Attach socket.io
 */
app.io.attach(server); 

/**
 * Listen on provided port, on all network interfaces.
 */
...

This code will attach to socket.io to the server declared just before.

Now we need to tell socket.io what he has to listen. To do that back to our app.js file and add this code just at the end of the file but important before module.exports = app;:

...
// start listen with socket.io
app.io.on('connection', function(socket){  
  console.log('a user connected');
});

module.exports = app;  

Open and edit the views\index.ejs file and add this code in the head tags:

...
<script src="/socket.io/socket.io.js"></script>  
<script>  
  var socket = io();
</script>  
...

From this time our application is ready to listen the new connection on the server, if you launch your app (npm start) and look at your console, the application should said the message a user connected when you browse the url http://localhost:3000. If you open a second browser on the same address, you will get again the same message and now two client are connected to the server.

Add some listener for messages

Now we need to listen when a new message is send by a user and send it to all connected user. To do that we will need to improve a bit our code in our app.js in the section socket.io:

...
// start listen with socket.io
app.io.on('connection', function(socket){  
  console.log('a user connected');

  socket.on('new message', function(msg){
    console.log('new message: ' + msg);
    app.io.emit('chat message', msg);
  });
});
...

With this code we will listen new messages from socket.on and we will broadcast them to all the connected client with app.io.emit.
From there our server side code has enough command to listen the client connection, when a message is send, and broadcast this message on all clients connected.

Add input and message area

For the next step we have to focus on the client side, by adding the input and send button, the message area and finally what we will do with the server when we send a message and receive one.
Go back to the file views\index.ejs edit the body like this

<body>  
  <h1><%= title %></h1>
  <h3>Welcome to <%= title %></h3>
  <ul id="messages-area"></ul>
  <form id="form" onsubmit="return false;">
    <input id="new-message" type="text" /><button onclick="sendFunction()">Send</button>
  </form>
</body>  

Till in the index.ejs edit the head script like this

<head>  
  <title><%= title %></title>
  <link rel='stylesheet' href='/stylesheets/style.css' />
  <script src="/socket.io/socket.io.js"></script>
  <script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
  <script>
  var socket = io();
  function sendFunction() {
    socket.emit('new message', $('#new-message').val());
    $('#new-message').val('');
  }
  socket.on('chat message', function(msg){
    $('#messages-area').append($('<li>').text(msg));
  });
  </script>
</head>  

From this time all of your application should now works. Try to run it with npm start and go to http://localhost:3000
Try to send a message, in the console you should see your message, and on your webpage this message should also displayed.
Ok right now is not so pretty, let improve a bit the style of our page.

Styling our webpage

First of all we need to change the title of the app, open the file call routes\index.js and replace Express by MyChat-App

...
* GET home page. */
router.get('/', function(req, res, next) {  
  res.render('index', { title: 'MyChat-App' });
});
...

Next we will replace the style.css by bootstrap to get a better style with less work :)
Edit the index.ejs and replace in the head tags <link rel='stylesheet' href='/stylesheets/style.css' /> by <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
Till in our index.ejs we need to add the classes of bootstrap and add some tags. You can replace all the body code by this

<body>  
  <div class="container-fluid">
    <div class="page-header">
      <h1><%= title %> <small>Welcome to <%= title %></small></h1>
    </div>

    <div class="row">
      <div class="col-sm-12">
        <ul id="messages-area" class="list-group"></ul>
      </div>
    </div>
  </div>

  <nav class="navbar navbar-default navbar-fixed-bottom">
    <div class="container-fluid">
      <form class="navbar-form" id="form" onsubmit="return false;">
        <div class="form-group"  style="width:83%">
          <input id="new-message" type="text" class="form-control" placeholder="Search" style="width:100%">
        </div>
        <button type="submit" class="btn ban-primary" onclick="sendFunction()" style="width:16%">Send</button>
        </form>
      </div>
    </nav>
  </body>

Restart your application and refresh your browser and should have now a nice design. This HTML code is not optimised and there is a lot of problems to fix, then now you know what to do :)

I hope you enjoyed to follow this small tutorial and it was not too-much confuse. I'll be happy to get feedback from you.

© 2017 Gulivert's Blog