Welcome to NODE.JS

Created by Kirill Kukhovets, specially for RS#5

What is NODE.JS?

WTF
  • Chrome's JavaScript runtime
  • C/C++
  • special I/O libs(Sockets, filesystem etc.)
  • non-blocking I/O model


"to provide a purely evented, non-blocking infrastructure to script highly concurrent programs"


Ryan Dahl

What is NODE.JS?

Q: JS on server? Why?

A: JavaScript is popular!

Q: JS on server? Why?

A: V8 is very fast!

Q: JS on server? Why?

A: Easy to bootstrap

Q: JS on server? Why?

A: Easy to bootstrap


var http = require('http');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n');
}).listen(8000);
   

OS support

  • Linux
  • OS X
  • Solaris
  • Windows

NODE.JS basics

Simple Application

helloworld.js

console.log("hello world!");
    
terminal

> cd working_folder
> node helloworld.js
    

Async

Async vs Sync

Sync I/O


var data = file.readSync('filename');
processFileData(data);
    

Async I/O


file.read('filename', function(data) {
    processFileData(data);
});
    

Async: Callback Hell

Async: Callback Hell


var main = function (arg1, callback) {
    read(arg1, function (err, arg2) {
        if (err) {
            callback(err);
        } else {
            update(arg2, function (err, arg3) {
                if (err) {
                    callback(err);
                } else {
                    save(arg3, function (err, arg3) {
                        if (err) {
                            callback(err);
                        } else {
                            callback(null, arg3);
                        }
                    })
                }
            })
        }
    })
}

    

Async: module sync


var main = function (arg1, callback) {
    sync(function () {
        var arg2 = read.sync(1,arg1);
        var arg3 = update.sync(2,arg2)
        var result = save.sync(3, arg3);
        return result;
    }, callback)
}
    

Async: module async(waterfall)


var main = function (arg1, callback) {
    var tasks = [function (callback) {
        read(arg1, callback)
    }, function (arg2, callback) {
        update(arg2, callback)
    }, function (arg3, callback) {
        save(arg3, callback)
    }];
    async.waterfall(tasks, callback);
}
    

Async: module Q(promises)


var main = function (arg1, callback) {
    read(arg1)
        .then(function (arg2) {
            return update(arg2)
        })
        .then(function (arg3) {
            return save(arg3)
        })
        .done(function (err, result) {
            return callback(result);
        })
}    

Events


var EventEmitter = require('events').EventEmitter;

var helloWorld = new EventEmitter();

helloWorld.on('hello', function(callback) {
  console.log('hello'.rainbow);
  callback();
});

worldCallback = function() { 
  console.log('world'.rainbow);
}

helloWorld.emit('hello', worldCallback);
   

Events: EventEmitter


emitter.addListener(event, listener)
emitter.on(event, listener)
emitter.once(event, listener)
emitter.removeListener(event, listener)
emitter.removeAllListeners([event])
emitter.setMaxListeners(n)
emitter.listeners(event)
emitter.emit(event, [arg1], [arg2], [...])

   

Modules: NPM

Modules: NPM

Modules: NPM


module.exports = {
    sleep: function(s) {
      var e = new Date().getTime() + (s * 1000);
      while (new Date().getTime() <= e) {
        ;
      }
    },

    usleep: function(s) {
      var e = new Date().getTime() + (s / 1000);
      while (new Date().getTime() <= e) {
        ;
      }
    }
  };
   

Modules: CommonJS

math.js


var PI = Math.PI; // ‘private’

sqr = function(x) {
  return x * x; // global scope
}
 
exports.area = function (r) {
  return PI * r * r; // ‘pubic’
};
 
exports.circumference = function (r) {
  return 2 * PI * r; // ’public’
};

   

Modules: Require

main.js

var math = require("./math.js");
console.log(math.area(10)); // 314.15926

   

Modules: Installation


> npm install module_name  //local folder node_modules

> npm install module_name -g //global installation 
			     //available for all local node.js apps(global tools)
   

Modules: NPM COMMANDS


> npm install module_name
> npm install module_name -g
> npm publish 
> npm search module_name
> npm uninstall module_name 
   

Modules: package.json


{
    "name": "best-practices",
    "description": "A package using versioning best-practices",
    "author": "ivan_ivanou@gmail.com",
    "dependencies": {
        "colors": "0.x.x",
        "express": "2.3.x",
        "optimist": "0.2.x",
        "plates"   :  "https://github.com/flatiron/plates/master"
    },
    "devDependencies": {
        “testLib": "0.5.x"
    },
    "engine": "node >= 0.4.1"
}

   

HTTP: SERVER


var http = require('http');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n');
}).listen(8000);
   

HTTP: SERVER

HTTP: CLUSTER


var cluster = require('cluster');
var http = require('http');
var numCPUs = require('os').cpus().length;
if (cluster.isMaster) {
  // Fork workers.
  for (var i = 0; i < numCPUs; i++) {
    cluster.fork();
  }
  cluster.on('exit', function(worker, code, signal) {
    console.log('worker ' + worker.process.pid + ' died');
  });
} else {
  http.createServer(function(req, res) {
    res.writeHead(200);
    res.end("hello world\n");
  }).listen(8000);
}
   

DB: Support

  • MySQL
  • Oracle
  • MSSQL
  • PostgreSQL
  • Redis
  • MongoDB
  • And others…

DB: ORM Define


var Person = db.define("person", {
    name      : String,
    surname   : String,
    age       : Number,
    male      : Boolean,
    continent : [ "Europe", "America", "Asia", "Africa", "Australia", "Antartica" ], // ENUM type
    photo     : Buffer, // BLOB/BINARY
    data      : Object // JSON encoded
}, {
    methods: {
        fullName: function () {
            return this.name + ' ' + this.surname;
        }
    },
    validations: {
        age: orm.enforce.ranges.number(18, undefined, "under-age")
    }
});
   

DB: ORM Usage


Person.find({ surname: "Doe" }, function (err, people) {
    // SQL: "SELECT * FROM person WHERE surname = 'Doe'"

    console.log("People found: %d", people.length);
    console.log("First person: %s, age %d", 
    	people[0].fullName(), people[0].age);

    people[0].age = 16;
    people[0].save(function (err) {
        // err.msg == "under-age";
    });
});
   

Node.js + Mongo DB = Love

What is Mongo DB?

  • Document-Oriented Storage
  • Full Index Support
  • Querying
  • GridFS
  • Commercial Support

Node.js + Mongo DB = Love

Example (mongodb module)


var databaseUrl = "mydb";
var collections = ["users", "reports"]
var db = require("mongojs")
    .connect(databaseUrl, collections);
 
db.users.find({sex: "female"}, function (err, users) {
    if (err || !users)
        console.log("No female users found");
    else
        users.forEach(function (femaleUser) {
            console.log(femaleUser);
        });
});
   

Node.js + Mongo DB = Love

Mongoose ODM Define


var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var UserSchema = new Schema({
  sex:  String,
  age: Number,
  body:   String,
  name: String,
  surname: String
});
var User = mongoose.model('User', UserSchema);
   

Node.js + Mongo DB = Love

Mongoose ODM Usage


User.find({sex: "female"}, function (err, users) {
    if (err || !users)
        console.log("No female users found");
    else
        users.forEach(function (femaleUser) {
            console.log(femaleUser);
        });
});
   

Node.js in industry

"Commercial" Node.js

Strong Loop

  • production support for node.js
  • slnode
  • private npm registry
  • supported npm modules

Thanks

Questions?

Useful links

nodejs.org
node.js sreencast

Contacts

kiryl.kuhovets@gmail.com