Tutorial

How To Install Express, a Node.js Framework, and Set Up Socket.io on a VPS

Published on August 27, 2013
Default avatar

By Aaron Shea

How To Install Express, a Node.js Framework, and Set Up Socket.io on a VPS

What You Will Learn In This Article


  • How to install NodeJS 0.10.16 using Node Version Manager (NVM)
  • How to install the Express web application framework for NodeJS
  • How to setup a simple Express project
  • How to setup socket.io in Express
  • Sending simple messages to the client in real-time
  • How to listen for messages using client-side javascript

Step 1: Setting up NodeJS


Note: You may skip this step if you already know you have NodeJS installed v0.10.16

Node Version Manager (NVM) is a tool to help install various versions of NodeJS on your linux machine. In order to use NVM ensure you have git and curl installed.

Connect to your VPS (droplet) using SSH.

If you do not have these installed, use your system’s package manager to install them. For example, on an Ubuntu or Debian install you would run:

```
sudo apt-get install curl git
```

Now you must run the NVM install script:

curl https://raw.github.com/creationix/nvm/master/install.sh | sh

IMPORTANT: You must now logout of your box and reconnect using SSH.

Test to make sure the nvm command works by typing nvm at the terminal. If you do not get a command not found error, then you have correctly setup NVM.

To install the latest version of Node (which is 0.10.16 at the time of this article), simply type:

nvm install 0.10.16

Then wait for the installation to complete. If the install was successful, you should get an output reading: Now using node v0.10.16.

Type node -v at the terminal to ensure you are using the specified version. You should get the output: v0.10.16

Step 2: Setting Up Express


Express is a web application framework for Node. It is minimal and flexible. In order to start using Express, you need to use NPM to install the module. Simple type:

npm install -g express

This will install the Express command line tool, which will aid in creating a basic web application. Once you have Express installed, follow these steps to create an empty Express 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”.

If you see the welcome message then you have a basic express application ready and running!

Be sure to kill your VPS with the Ctrl+C keyboard command before you keep going.

Step 3: Installing Socket.io Into Your Express Application


First, a quick summary of what Socket.io is. 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.

So how do you get started with this? First you need a Socket.io server. We already have an Express server ready and waiting, all we need to do is add on the socket library. To do that we have to 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.

Part 4: The Server Code


Now that we have all the dependencies set up, we can start the code! Go and 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.

Now how do we transport a message to the user?

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.

Part 5: The 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.

Switch back into the socketio-test directory:

cd socketio-test

Save the layout file and start your Express app once again using: node app.

Part 6: Testing It


Now navigate your browser once more to http://yourDropletIp-or-domainName:3000 and open the developer tools console. You should see something like this in the log:

Object {msg: "The world is round, there is no up or down."}

This is a message sent directly from the VPS to the client in real-time.

<div class=“author”>Submitted by: <a href=“https://twitter.com/aaron524web”>Aaron Shea</a></div>

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about us


About the authors
Default avatar
Aaron Shea

author

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
10 Comments


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

When I try to install socket.io in Ubuntu using npm I get fetch failed error. My connection is active and am able to access the links in the error message from the browser.

npm ERR! fetch failed https://github.com/rase-/node-XMLHttpRequest/archive/a6b6f2.tar.gz
 
> ws@0.5.0 install /home/arun/GitProjects/selfie-showcase/node_modules/socket.io/node_modules/engine.io/node_modules/ws
> (node-gyp rebuild 2> builderror.log) || (exit 0)

make: Entering directory `/home/arun/GitProjects/selfie-showcase/node_modules/socket.io/node_modules/engine.io/node_modules/ws/build'
  CXX(target) Release/obj.target/bufferutil/src/bufferutil.o
  SOLINK_MODULE(target) Release/obj.target/bufferutil.node
  SOLINK_MODULE(target) Release/obj.target/bufferutil.node: Finished
  COPY Release/bufferutil.node
  CXX(target) Release/obj.target/validation/src/validation.o
  SOLINK_MODULE(target) Release/obj.target/validation.node
  SOLINK_MODULE(target) Release/obj.target/validation.node: Finished
  COPY Release/validation.node
make: Leaving directory `/home/arun/GitProjects/selfie-showcase/node_modules/socket.io/node_modules/engine.io/node_modules/ws/build'
npm ERR! fetch failed https://github.com/rase-/node-XMLHttpRequest/archive/a6b6f2.tar.gz
npm ERR! fetch failed https://github.com/rase-/node-XMLHttpRequest/archive/a6b6f2.tar.gz
npm ERR! network tunneling socket could not be established, cause=getaddrinfo ENOTFOUND
npm ERR! network This is most likely not a problem with npm itself
npm ERR! network and is related to network connectivity.
npm ERR! network In most cases you are behind a proxy or have bad network settings.
npm ERR! network 
npm ERR! network If you are behind a proxy, please make sure that the
npm ERR! network 'proxy' config is set properly.  See: 'npm help config'

npm ERR! System Linux 3.13.0-32-generic
npm ERR! command "/usr/local/bin/node" "/usr/local/bin/npm" "install" "--no-proxy"
npm ERR! cwd /home/arun/GitProjects/selfie-showcase
npm ERR! node -v v0.10.36
npm ERR! npm -v 1.4.28
npm ERR! code ECONNRESET
npm ERR! not ok code 0

This is completely out of date… following those instructions won’t get you anywhere but in errors. Why you just don’t up date it in order for people trying to learn it be helped instead of getting more confused!

Hi there I want to use Express. The first steps was to :1) sudo apt-get install curl git 2) curl https://raw.github.com/creationix/nvm/master/install.sh | sh

I have tried those two installations, and then test if the installations was right installed by typing nvm - but I got the message “nvm: command not found”

I hope to hearing from you.

Just a heads up, for the curl command you may have to add the -L flag since the file has moved curl -L https://raw.github.com/creationix/nvm/master/install.sh | sh

I get this error, any suggestion on how to correct it? /root/socketio-test/app.js:9 var app = express(); ^ TypeError: object is not a function at Object.<anonymous> (/root/socketio-test/app.js:9:11) at Module._compile (module.js:456:26) at Object.Module._extensions…js (module.js:474:10) at Module.load (module.js:356:32) at Function.Module._load (module.js:312:12) at Function.Module.runMain (module.js:497:10) at startup (node.js:119:16) at node.js:902:3

Having wasted a lot of time trying to follow this with one of the Ubuntu node-v0.12.5 on 14.04 pre-configured droplets, you’re far better off skipping from step 2 onwards and following the tutorials on the socket.io site e.g http://socket.io/get-started/chat/ - these are more likely to be kept up to date with later versions of express and socket syntax…

This misses out the step where you have to create a service.

Otherwise you will need to have your server running in a xterm window and would never be able to log out of your server.

It also misses the step where CORS gives you a total nightmare.

How to setup socket for linux? Help me…

Any detailed tutorial for running multiple socket.io servers and nginx load balancing/ reverse proxying it ?

Like @malist , I had to do sudo npm install -g express-generator in Ubuntu 14.04. According to http://stackoverflow.com/questions/23097826/install-express-with-npm Its a change since Express 4 that I think would apply on any Operating System. Its in the readme for the express install as well

After that step, @bosslee above, running ‘node app’ didnt work for me, it returned to the command prompt without any message. Whereas this did, npm start as mentioned in the express readme and here https://github.com/expressjs/generator Also, If you’ve followed the other DO Ubuntu/node install guides, remember to open port 3000 on the firewall

sudo ufw allow 3000/tcp sudo ufw reload

Maybe the guide could be updated to reflect these changes

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Get our biweekly newsletter

Sign up for Infrastructure as a Newsletter.

Hollie's Hub for Good

Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

Become a contributor

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

Welcome to the developer cloud

DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

Learn more
DigitalOcean Cloud Control Panel