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
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.
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.
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.
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
.
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.
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.
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