ExpressJS - Guide #2

expressjs

https://www.digitalocean.com/community/tutorials/how-to-install-express-a-node-js-framework-and-set-up-socket-io-on-a-vps - done reading, good

How can we install express?

npm install -g express

How can we start a project?

mkdir socketio-test
cd socketio-test
express
npm install

These commands will create an empty Express project in the directory we just created socketio-test. We then run npm install to get all the dependencies that are needed to run the app. To test the empty application, run node app then navigate your browser to http://yourDropletIp-or-domainName:3000. You should get a simple welcome message saying: "Welcome to Express".

What is socket.io?

Socket.io is a real-time JavaScript library. In short, it's a WebSocket API that will determine the correct type of connection to make depending on the browser's capabilities, whether it be AJAX Long Polling, Flash, or even just plain WebSockets.

How can we add socket.io to our express application?

Add it to the package.json file. Your initial file might look something like this:

{
  "name": "application-name",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "node app.js"
  },
  "dependencies": {
    "express": "3.3.5",
    "jade": "*"
  }
}

Now add a new field to the "dependencies" area:

"socket.io": "latest",

Your resulting file should look something like this:

{
  "name": "application-name",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "node app.js"
  },
  "dependencies": {
    "socket.io": "latest",
    "express": "3.3.5",
    "jade": "*"
  }
}

Now run npm install once more to install the socket library:

npm install

Open up the app.js file in the Express application folder. Inside you'll a bunch of auto-generated code, delete all of it and use the following example instead:

/**
 * Module dependencies.
 */

var express = require('express')
  , routes = require('./routes')
  , http = require('http');

var app = express();
var server = app.listen(3000);
var io = require('socket.io').listen(server); // this tells socket.io to use our express server

app.configure(function(){
  app.set('views', __dirname + '/views');
  app.set('view engine', 'jade');
  app.use(express.favicon());
  app.use(express.logger('dev'));
  app.use(express.static(__dirname + '/public'));
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(app.router);
});

app.configure('development', function(){
  app.use(express.errorHandler());
});

app.get('/', routes.index);

console.log("Express server listening on port 3000");

All this example file has done has reorganized the auto-generated code and added the var io = require('socket.io').listen(server); line which tells socket.io to listen on and use our Express server. If you run your node app you should see it output: info - socket.io started.

How can we transport message to the browser?

Add the following lines to your app.js just below the last line.

io.sockets.on('connection', function (socket) {
    console.log('A new user connected!');
    socket.emit('info', { msg: 'The world is round, there is no up or down.' });
});

This will send out a new socket message whenever a new user connects to the server. Now we just need a way to interact with the VPS on the client side.

How can we add client-side code?

Naviagate to the public/javascripts folder inside your Express application and add a new file called client.js and put this code into it:

// connect to the socket server
var socket = io.connect(); 

// if we get an "info" emit from the socket server then console.log the data we recive
socket.on('info', function (data) {
    console.log(data);
});

The code is simple but it demonstrates what you can do with Socket.io. Now we just need to include the scripts into our main page. Navigate to your views folder in the Express app and open layout.jade. Express does not use plain HTML to render its pages. It uses a templating engine called Jade. (More information about Jade can be found here) Jade is simple and clean compared to plain HTML. To add our client script and add the Socket.io client library we simple need to add these to lines just below the link(rel='stylesheet', href='/stylesheets/style.css'):

script(type='text/javascript', src="/socket.io/socket.io.js")
script(type='text/javascript', src='javascripts/client.js')

Make sure they line up on the same indent level and do NOT mix tabs and spaces. This will cause Jade to throw an error.

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License