NodeJS:
JavaScript On The Other Side

@imcoddy
2011-07-10

JavaScript runs on the server side?
You gotta be kidding me!
Many JS Programmers

Evolution of JavaScript

To provide a purely evented, non-blocking infrastructure to script highly concurrent programs.
The Node.JS Project

What is NodeJS?

Node.JS is not a JS framework, but a JS interpreter

Hello World, in Node's Way.

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

6 LoC to create a http server.

Why NodeJS?

I/O Latency

L1: 3 cycles

L2: 14 cycles

RAM: 250 cycles

Disk: 41,000,000 cycles

Network: 240,000,000 cycles

source: http://s3.amazonaws.com/four.livejournal/20091117/jsconf.pdf

Blocking vs Non-blocking

The blocking way:

var result = db.query("select..");
print('I can not print until the result is returned.')
print('And the I/O is damn SLOW.');
do_something_with_result(result);

The non-blocking way:

db.query("select..", function (result) {
   print('Handle the result now.');
   do_something_with_result(result);
});
print('No more waiting.');
print('Do the following right away');
do_something_else();
Everything runs in parallel, EXCEPT YOUR CODE.
Philosophy of NodeJS

Struture of NodeJS

source: http://s3.amazonaws.com/four.livejournal/20091117/jsconf.pdf

Why JavaScript Suits NodeJS?

NodeJS brings the power of JavaScript to the server side.

Node express demo

The Node Ecosystem

Over 4700 watchers on Github

More than 1600 modules posted

60+ contributors

3 books in progress

1 command to install: npm install module-you-want

0.5 unstable version just released

Gets better everyday

NodeJS Limitations

Hard core CPU calculating

Large content transfer

1G memory limit due to V8 engine

Something Bothering Me

NodeJS makes thinking differently

var data = {}
db.getPosts(10, function(err,posts){
 data.posts = posts;
});
db.getComments(10, function(err, comments){
 data.comments = comments;
});      
db.getTags(function(err, tags){
 data.tags = tags;
})
 
// view.render(data)
// How do you know when everything is ready?
http://www.slideshare.net/QLeelulu/nodejs-8283613

NodeJS makes thinking differently (cont.)

function Combo(callback){
 this.callback = callback;
 this.items = 0;
}      
Combo.prototype = {
 add: function(){
   this.items++;
 },
 finishOne: function(){
   this.items--;
   this.check();
 },
 check: function(){
   if(this.items === 0){
     this.callback.apply(this);
   }
 }
};

NodeJS makes thinking differently (cont.)

var data = {};
var combo = new Combo(function(){
 view.render(data);
});
combo.add();
db.getPosts(10, function(err,posts){
 data.posts = posts;
 combo.finishOne();});
combo.add();
db.getComments(10, function(err, comments){
 data.comments = comments;
 combo.finishOne();});
combo.add()
db.getTags(function(err, tags){
 data.tags = tags;
 combo.finishOne();})  

The Long And Deep Callback Chain

self.handleQuery = function(client, message) {
 var query = message.query;
   Blip.query(query).all(function(results) {
     client.send(
       {buffer:
         results.map(
           function(msg) {
             return {message: {
                 sender: msg.sender,
                 content: msg.content,
                 }
              }
           }
        )
     });
 });
};

Well, You Can Make It Shorter With CoffeeScript

@handleQuery = (client, message) ->
 Blip.query(message.query).all (results) ->
   client.send buffer:
     results.map (msg) ->
       message:
         sender: msg.sender
         content: msg.content

Async Makes Testing Difficult

collection = 'test'
query = {}
app.count collection,query,(count)->
  doc = 
    name:1
  app.save collection,doc,()-> 
    console.log 'save in '+collection
    app.count collection,query,(result)->
       assert.eql count+1,result
collection = 'product'
// save action was supposed to execute in the 'test' collection
// but it will actually be saved in 'product' collection!

The Future Node

Windows porting with MS offical support

New networking layer

Long traceback

...

Linux + Node.js + MongoDB:

The new LAMP is on the way

Resources

http://nodejs.org/

http://github.com/ry/node/wiki

http://howtonode.org/

http://dailyjs.com/

http://cnodejs.org/