Node.js Tutorial

Server side javascript ! sounds wow right. Node.js is nothing but javascript executing at the server. It uses Google v8 engine.v8 engine is used by chrome browser to execute javascript.Node is evented I/O which makes it non blocking. Thus it is efficient.

Why Javascript?

Javascript has the ability to pass the reference of the function to an another function.Which makes it make a callback once the event fires.

Whats New ?

Traditional approch used to serve a webpage is using multi threads for concurrent connections between the clients.But node instead uses only one thread that handles all the connection using a event loop.

Lets Gets Started:

 INSTALLATION: 

http://nodejs.org/ – You could install it from this website.

SAMPLE  HELLO WORLD CODE:

var http = require('http');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n');
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');

When ever a request is made to the server a call back function is called to handle the request. This is like creating our own server where we handle the every request and respond the respective html files as response.

HANDLING DIFFERENT REQUEST – MULTI PAGE APPLICATION

Now you will get a confusion. If there is only one call back function for our server. How to serve different pages in our application.All these works has to be done by our call back function. We should parse the URL and get the request and based on the request we should respond.Following codes will handle it.

var app = require('http').createServer(handler)
  , qs = require('querystring')
   ,url = require('url')
   app.listen(8080);

function handler (request, response)
{

          var parsedURL = url.parse(request.url, true);
          var path = parsedURL.pathname;
          var query = parsedURL.query;
          switch (path)
          {

            case '/index':
                res.writeHead(200, {'Content-Type': 'text/plain'});
                es.end('INDEX PAGE\n');

            break;

            case '/home':
                res.writeHead(200, {'Content-Type': 'text/plain'});
                es.end('HOME PAGE\n');

            break;

            default:
                res.writeHead(200, {'Content-Type': 'text/plain'});
                es.end('ERROR\n');
            break;

          }

}

Fileserver :

A fileserver module is there in the node.js to serve the file. Thus based on the request from the client ,we could serve a file.The file may be anything , a html,css, or js file.To make it clear. Lets look at a code.

switch (path)
{

case '/jquery.js':
  fs.readFile(__dirname + '/jquery.js',
  function (err, data) {
    if (err) {
      response.writeHead(500);
      return response.end('Error loading index.html');
    }

    response.writeHead(200);
    response.end(data);
  });
  break;

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

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

break;
}

If you are using a external  javascript file. You need to serve that file also . Even though you link your js file with your index.html page. Unless you handle that request in your server it wont take it.

Node.js Chat Example:

Lets make a real time app. First we need to install a module socket.io.

INSTALLATION:

http://socket.io/ – You could install it from this link.

IDEA:

Idea is simple. When ever client request, initially we get their name and sends this data to the server and save it in a session variable  Session variable- A data stored about a client in server. You can access at any point of time. When ever a user types and clicks send button the data what he typed is sent to the server and broadcast ed to all the clients connected. Here a event name is assigned in socket.io.Such that in occurrence of a particular event a data’s are broadcast ed to that client that containing that event name.

 IMPLEMENTATION:

Server:

io.sockets.on('connection', function (socket)
{
      socket.on('session', function (name)
      {
         socket.set('name', name, function ()
         {
           console.log(name);
         });
      });

      socket.on('msg', function (chat)
      {
         socket.get('name', function (err, name)
         {
           socket.broadcast.emit('chat',  chat );
         });
      });
});

Client:

var name=window.prompt("ENTER YOUR NAME");
var socket = io.connect('http://localhost:8080');
socket.emit('session',name);
socket.on('chat', function (chat)
{

  $('#chat').append(chat);
});
function GetValue()
{
  var str=$('#chattext').val();
  var message='<b>'+name+'</b>:'+str+'<br>';
  socket.emit('msg',message);
  $('#chat').append(message);
  $('#chattext').attr('value', '');
}

The above code is the implementation of the idea .This is a simple broadcast chat application using node.js. You could download the source code and play it around with it.Feel free to comment your queries.

 

0saves
If you like this post, contribute us by sharing this in your network
  • http://weblogs.asp.net/yuanjian/archive/2013/03/02/cheatsheet-2013-02-16-02-28.aspx Cheatsheet: 2013 02.16 ~ 02.28 – gOODiDEA.NET

    [...] Node.js Tutorial [...]

  • http://www.webtuts.info/node-js/node-js-tutorial-beginners/999/ Node.js Tutorial For Beginners | WEBTUTS

    [...] [...]

Ver peliculas online