How to install Node.js, npm, socket.io and use them?

1 Go to http://nodejs.org and click on Install button, 
2.. Download node and install it
3.. Create an empty folder on your hard disk
     3.1) check environment path of nodejs using command prompt
            a) C:\>set %PATH%
             If it is not showing any path regarding node then set the environment path
            b) C:\>set path=%PATH%;C:\Program Files\nodejs\
4.. Create an package.json file with the following content
      Ex: C:\Program Files\nodejs\package.json
{
    "name": "App",
    "version": "0.0.1",
    "description": "App",
    "dependencies": {
        "socket.io": "latest"
    },
    "author": "developer"
}
5.. Open windows's command prompt (press Windows key + R and type cmd)
6.. Navigate to your newly created directory with cd command
7.. Type npm install in that directory
      7.1) If you face any problem like file not found for package.json then go to nodejs path
             C:\Program Files\nodejs\ and then type npm install
8.. Wait till everything is downloaded and installed
9.. Create a file app.js with the following content:
var app = require('http').createServer(handler)
  , io = require('socket.io').listen(app)
  , fs = require('fs')

app.listen(3000);

function handler (req, res) {
  fs.readFile(__dirname + '/index.html',
  function (err, data) {
    if (err) {
      res.writeHead(500);
      return res.end('Error loading index.html');
    }

    res.writeHead(200);
    res.end(data);
  });
}

io.sockets.on('connection', function (socket) {
  socket.emit('news', { hello: 'world' });
  socket.on('my other event', function (data) {
    console.log(data);
  });
});
10.. Create a file index.html with the following content
<script src="/socket.io/socket.io.js"></script>
<script>
  var socket = io.connect('http://localhost');
  socket.on('news', function (data) {
    console.log(data);
    socket.emit('my other event', { my: 'data' });
  });
</script>
11.. Again, go to the command prompt (console) and type node app.js. This will run nodejs server and you may open localhost:3000

Comments

Popular posts from this blog

AIOMgr: Preparing flush failed with VERR_NOT_SUPPORTED, disabling async flushes

Create Virtual Host in IIS Server

The model type is invalid. please select an item from the list ( ASP.Net MVC)