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
cd node
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, ""); 
console.log('Server running at');

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");

server.listen(8124, "");

HTTP CLIENT with node.js

var http = require('http');

var params = {
  host: '',
  port: 80,
  path: '/',
  method: 'GET'

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


// RAW Data

var req = http.get({host:'', port:80, path:'/'}, function(res) { 
    res.on('data', function(c) { 

// End

// UTF8 encoded 
var req = http.get({host:'', port:80, path:'/'}, function(res) { 
    res.on('data', function(c) { 

// Indeed 

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