Node.js

Agenda

  • Install
  • Hello World
  • Ecosystem
  • Single threaded
  • Blocking IO
  • Servers TCP/HTTP
  • CTF

Install Node.js


http://nodejs.org

follow wizard

Installed?


$ node --version
v0.10.30


REPL

$ node 
>

$ node 
> var hello = "world"; undefined >

> hello
'world'
>

Hello world!


var http = require('http'); 

var server = http.createServer(function(req, res){
    res.end("Hello World");
});

server.listen("3000");

Node is

  • v8 JavaScript runtime
  • Event driven
  • Non-blocking standard libraries
  • Extend with C/C++ addons

Node is not

  • A framework
  • A new programming language

What is Node used for?

Web servers
Desktop applications
CLI tools

Websites!


Desktop applications!


CLI tools


Why?

  • JavaScript everywhere!
  • Great community (NPM, sponsors)


Sweet Spots!

  • Real Time IO intensive apps
  • Speaks JSON
  • Easy to make APIs

Not so sweet..

  • Simple crud apps
  • CPU intensive stuff

Ecosystem

  • NPM
  • Bower
  • Grunt
  • Yeoman
  • MongoDB (and other)
  • Template engines

DEMO 1.5

What's taking so long?!

  • L1-cache: 3 cycles
  • L2-cache: 14 cycles
  • RAM: 250 cycles
  • Disk: 41 000 000 cycles
  • Network: 240 000 000 cycles

So: what is non-blocking IO 
with these facts in mind?

Sync vs. Async


Node runs on 1 thread only

Almost...

Disk operations and network requests are threaded.
But you can't interfere with those

DEMO 2!


First thing every programmer do...



cout << "Tell me your name: ";
cin >> name;
cout << "Hello " << name << endl;


Let's do that async


process.stdout.write("Tell me your name: ");

process.stdin.on('data', function(name){
    console.log("Hello " + name);
});

WEBSERVERS!


TCP and HTTP

TCP

var tcp = require('net');
var server = tcp.createServer();

server.on('connection', function(connection){
    console.log(connection);
});

server.listen(3000);
Which event are available?

HTTP & DEMO 3

var http = require('http');
var server = http.createServer();

server.on('request', function(req, res){
    res.end("You requested: " + req.headers.host);
});

server.listen(3000);

ORC API

var tcp = require('net');
var stdin = process.openStdin();
var client = tcp.connect('PORT', 'HOST/IP'); client.setEncoding('ENCODING');

stdin.addListener("data", function(d){ ... });

client.on('connect', function(){ ... });
client.write("STRING");
client.on('data', function(data){ ... });
IP: xx.xx.xx.xx
Port: 3000

"JOIN nickname"


Next time?

Connect
Express

Node.JS #1

By Gustav Jorlöv

Node.JS #1

  • 579