New Kid On The Block – Node.js


Joel Divekar
GM – Information Systems,
People Interactive (I) Pvt. Ltd.
Open Source Conference, Pune
23rd March, 2013
Node.js was developed by Ryan Dhal in 2009
   and the project is managed by Joyent
Node.js is ...

Server side JavaScript

    Event Driven

  Asynchronous I/O

  Single Threaded

    Lightweight
Node.js ...

High performance network application framework and can
easily handle thousands of concurrent connections with
minimum CPU / Memory Utilisation



Built on top of Google's V8 JavaScript engine used in
Chrome



Easy to build scalable network servers
Node.js is similar to ...


EventMachine in Ruby


Twisted in Python
I/O
Blocking I/O
var fs = require('fs');

var file1 = fs.readFileSync('File1.txt', 'utf­8');

console.log(“Reading File1.txt”);

var file2 = readFileSync('File2.txt', 'utf­8');

console.log(“Reading File2.txt”);

Non-Blocking I/O
var fs = require('fs');

fs.readFileSync('File1.txt', 'utf­8', function(err,data){

    console.log(“Reading File1.txt”)

});

fs.readFileSync('File2.txt', 'utf­8', function(err,data){

    console.log(“Reading File2.txt”)

});
I/O
Blocking I/O
Reading File1.txt took 10 ms
Reading File2.txt took 6 ms
Total time 16 ms




Non-Blocking I/O
Reading File1.txt took 10 ms
Reading File2.txt took 6 ms
Total time 10 ms
Callback
//callback after 2 seconds
setTimeout(function(){
    console.log(“World”);
}, 2000);
    console.log(“Hello”);
Node REPL
REPL : Read - Eval - Print - Loop
$ node

> a=[1,2,"3",'four',];

[ 1, 2, '3', 'four' ]

> a.forEach(function (v) {

... console.log(v);

... });

1

2

3

four

Undefined

> .exit
Node.js HTTP Server
var http = require("http");

http.createServer(function(req, res) {

req.on("end", function () {

res.writeHead(200, {'Content­Type' : 'text/plain'});

res.end('Your IP is ' + (req.headers['x­forwarded­for'] || 
   req.connection.remoteAddress) + '!') });

}).listen(8080);



console.log("Server accepting request on http://127.0.0.1:8080");
Node.js HTTP Server
var http = require("http");

http.createServer(function(req, res) {

req.on("end", function () {

res.writeHead(200, {'Content­Type' : 'text/plain'});

res.end('Your IP is ' + (req.headers['x­forwarded­for'] || 
   req.connection.remoteAddress) + '!') });

}).listen(8080);



console.log("Server accepting request on http://127.0.0.1:8080");
npm
npm is package manager for node.js, similar to RubyGems &
  Python easy_install


npm install <module_name>


Modules
Express – MVC framework
Socket.IO – Websocket Library
Who is using Node.js ...
Thanks a lot for your time …
    joel.divekar@gmail.com
 www.linkedin.com/in/joeldivekar
   joeldivekar.blogspot.com
 www.slideshare.net/JoelDivekar

New kid on the block node.js