Server-Side JavaScript with Node.js

node.js => evented I/O for v8 javascript

<

p>Installing node.js on a Debian machine :

sudo apt-get install g++ curl libssl-dev apache2-utils git-core
git clone http://github.com/joyent/node.git
cd node
./configure
make
sudo make install

Check for help :

$ node
> .help
.clear    Break, and also clear the local context.
.exit    Exit the prompt
.help    Show repl options

Hello Node!

cat > hello.js
var sys = require("sys"); 
sys.puts("Hello Node!");

Now in the same terminal do a node hello.js and you will see Hello Node! Sounds like fun? Lets see more of it!

HTTP server that responds as Hello Node!

cat > server.js
var http = require('http'); 
http.createServer(function (req, res) { 
    res.writeHead(200, {'Content-Type': 'text/plain'}); 
    res.end('Hello Node!\n'); 
}).listen(8124, "127.0.0.1"); 
console.log('Server running at http://127.0.0.1:8124/');

Now running node server.js will print the url link as in the console.log(); open that link will render Hello Node! On the browser!

One line HTTP Server with Node.js!

require('http').createServer(function(req,res){res.writeHead(200, {}); res.end('Hello Node!');}).listen(8125);

The above line is just for the fun of it and no one is supposed to write such clumsy CODE. What basically that line does is it includes http module, invoke createServer() to which a function to handle the request event is passed which listens to port 8125.

TCP server with Node.js

var net = require('net');

var server = net.createServer(function (socket) {
  socket.write("Echo server\r\n");
  socket.pipe(socket);
})

server.listen(8124, "127.0.0.1");

HTTP CLIENT with node.js

var http = require('http');

var params = {
  host: 'www.google.com',
  port: 80,
  path: '/',
  method: 'GET'
};

var req = http.request(params, function(res) {
  console.log(res);
  res.on('data', function(data) {
    console.log(data);
  });
});

req.end();

// RAW Data

var req = http.get({host:'www.google.com', port:80, path:'/'}, function(res) { 
    console.log(res); 
    res.on('data', function(c) { 
       console.log(c); 
    }); 
});

// End
req.end();

// UTF8 encoded 
var req = http.get({host:'www.google.com', port:80, path:'/'}, function(res) { 
    res.setEncoding('utf8'); 
    res.on('data', function(c) { 
        console.log(c); 
    }); 
});

// Indeed 
req.end();

So far was just a glimpse of node.js much much more is doable with it, have fun! Do share your code below!

Share this