node.js

12
[email protected] 25. Mai 2011 Design and Construction of Distributed Enterprise Applications TU Darmstadt, SS 2011

Upload: jan-dillmann

Post on 27-Nov-2014

7.135 views

Category:

Technology


5 download

DESCRIPTION

 

TRANSCRIPT

Page 1: Node.js

[email protected]

25. Mai 2011

Design and Construction of Distributed Enterprise Applications

TU Darmstadt, SS 2011

Page 2: Node.js

What?

”Node's goal is to provide an easy way to build scalable network programs.“

—nodejs.org

2

Page 3: Node.js

Keeping slow operations fromblocking other operations.

How?

3

Page 4: Node.js

Traditional I/O

var results = db.query("SELECT * FROM TABLE");

for (var i=0; i<results.length; i++) {

// process query result

}

// do something else

// zzzzZZZzzzzz

4

Page 5: Node.js

Asynchronous I/O

db.query("SELECT * FROM TABLE", function(results) {

for (var i=0; i<results.length; i++) {

// process query result

}

});

// do something else immediately

5

Page 6: Node.js

And how many threads?

6

ONLY ONE THREAD?!threading ain't free

easy to code

no deadlocks

no race-conditions

Page 7: Node.js

var http = require('http');

var sqlite3 = require('sqlite3');

var db = new sqlite3.Database('sample.db');

http.createServer(function(request, response) {

response.writeHead(200, {"Content-Type": "text/plain"});

db.all("SELECT * FROM names", function (err, rows) {

rows.forEach(function(row) {

response.write(row.name + ' ' + row.surname + ' (' + row.email + ')\n');

});

response.end();

});

}).listen(8000);

console.log("Running at http://127.0.0.1:8000/");

7

$ node httpsqlite.js

Page 8: Node.js

8

But how does it work?client node http sqlite db

get rows

write response

response

request

SELECT * FROM ...

execute query

create server

console.log listen on 8000

Page 9: Node.js

In other words:

”With an event loop, you ask it to do something and it'll get back to you when it's done.“

—@davidpadbury

9

Page 10: Node.js

So … what is in there?

LIBEV LIBEIO

GOOGLE V8

10

… and more

ServerSide

JavaScript

compiles JavaScript toAssembler

EventLoop evented

file I/O

Page 11: Node.js

node.js 101

Server Side JavaScript

Built on Googles V8

Evented, non-blocking I/O

Single threaded

Everything is asynchronous

Modules for (nearly) everything

Currently only for unix-based systems available *

11* on Windows, you can try cygwin, but that is like asking for trouble...