node.js - blurring the line between client and server var title = “ node.js - blurring the line...

26
var title = “Node.JS - Blurring the Line Between Client and Server”; $(this).attr(“title”, title); $(this).data({ font: ‘Segoe UI’, size: ‘30pt’, maxLines: ‘3 lines max’ });

Upload: devin-stamer

Post on 01-Apr-2015

226 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Node.JS - Blurring the Line Between Client and Server var title = “ Node.JS - Blurring the Line Between Client and Server ”; $(this).attr(“title”, title);

var title = “Node.JS - Blurring the Line Between Client and Server”;$(this).attr(“title”, title);$(this).data({

font: ‘Segoe UI’, size: ‘30pt’, maxLines: ‘3 lines max’

});

Page 2: Node.JS - Blurring the Line Between Client and Server var title = “ Node.JS - Blurring the Line Between Client and Server ”; $(this).attr(“title”, title);

Agenda

• Why Node.JS?o Why yet another server framework?

• What is it?o Asynchronous IO and the Evented Model

• Hands Ono Let’s write some codeo How to nodeo Package, frameworks and toolso Latest features

• Q&A

Page 3: Node.JS - Blurring the Line Between Client and Server var title = “ Node.JS - Blurring the Line Between Client and Server ”; $(this).attr(“title”, title);

JavaScript on the Server

Pros• It’s JavaScript – it’s the best!• It’s fast and easy to scale• One language to rule them

allo Share code across

client/servero Never write serialization

code again – it’s all JSON

• Never debug multithreaded code again

• More?

Cons• It’s JavaScript – is it even a

real language?• Async programming – can

be unfamiliar and hard• Nested callback hell• Single process doesn’t

scale across cores

• More?

Page 4: Node.JS - Blurring the Line Between Client and Server var title = “ Node.JS - Blurring the Line Between Client and Server ”; $(this).attr(“title”, title);

ORIGINSWhy yet another server framework?

Page 5: Node.JS - Blurring the Line Between Client and Server var title = “ Node.JS - Blurring the Line Between Client and Server ”; $(this).attr(“title”, title);

Evolution of Socket Servers

• In the beginning was CGIo A new process per request

• Worker Pool Modelo Dispatch requests to persistent worker pool

• To infinity and beyondo The C10k problemo The race for high throughput and low latency

Page 6: Node.JS - Blurring the Line Between Client and Server var title = “ Node.JS - Blurring the Line Between Client and Server ”; $(this).attr(“title”, title);

Thread Pool Model

responsesrequest queue

thread pool

thread 1

thread 2

thread 3

thread 4

thread n

concurrency = # threads

Page 7: Node.JS - Blurring the Line Between Client and Server var title = “ Node.JS - Blurring the Line Between Client and Server ”; $(this).attr(“title”, title);

Worker Thread Efficiency

wait… wait… wait…

route, parse requestform db query

parse db resultform web service query

process results

form response

db query web servicequery

log to disk

wait… wait… wait…

wait… wait… wait…wait… wait… wait…

Page 8: Node.JS - Blurring the Line Between Client and Server var title = “ Node.JS - Blurring the Line Between Client and Server ”; $(this).attr(“title”, title);

Relative I/O Latency

CPU cycles

L1 cache 3

L2 cache 14

RAM 250

disk 41 000 000

network 240 000 000

Relative

next room ~5m

across the street ~20m

next block ~400m

Earth circumference

distance to the Moon

Page 9: Node.JS - Blurring the Line Between Client and Server var title = “ Node.JS - Blurring the Line Between Client and Server ”; $(this).attr(“title”, title);

IS THERE A BETTER WAY?

Page 10: Node.JS - Blurring the Line Between Client and Server var title = “ Node.JS - Blurring the Line Between Client and Server ”; $(this).attr(“title”, title);

Asynchronous I/O

1. Start I/O and return (non-blocking)2. Perform other tasks3. When I/O completes, process the result

• Handle requests in a single thread• Popular examples: nginx, lighttpd

Page 11: Node.JS - Blurring the Line Between Client and Server var title = “ Node.JS - Blurring the Line Between Client and Server ”; $(this).attr(“title”, title);

Node.JS in 5 words

Evented I/O for V8 JavaScript

Page 12: Node.JS - Blurring the Line Between Client and Server var title = “ Node.JS - Blurring the Line Between Client and Server ”; $(this).attr(“title”, title);

Evented Model

eventqueue

eventloop

single-thread

user space

I/O done

network

file system

other

internalthread pool

Page 13: Node.JS - Blurring the Line Between Client and Server var title = “ Node.JS - Blurring the Line Between Client and Server ”; $(this).attr(“title”, title);

Async Callbacks – Look Familiar?

setTimeout(function() {    console.log("time's up")}, 1000); console.log('hello')

while (true) {}

Page 14: Node.JS - Blurring the Line Between Client and Server var title = “ Node.JS - Blurring the Line Between Client and Server ”; $(this).attr(“title”, title);

HANDS ONLet’s write some code

Page 15: Node.JS - Blurring the Line Between Client and Server var title = “ Node.JS - Blurring the Line Between Client and Server ”; $(this).attr(“title”, title);

“Hello, World!”

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

Page 16: Node.JS - Blurring the Line Between Client and Server var title = “ Node.JS - Blurring the Line Between Client and Server ”; $(this).attr(“title”, title);

Static HTTP Server

var http = require('http')var fs = require('fs') http.createServer(function(req, res) {     fs.readFile('index.html', function(err, data) {        if (err) {            res.writeHead(500)            res.end()        } else {            res.end(data)        }    })}).listen(9090)

Page 17: Node.JS - Blurring the Line Between Client and Server var title = “ Node.JS - Blurring the Line Between Client and Server ”; $(this).attr(“title”, title);

Let’s codeWriting a simple blog

Page 18: Node.JS - Blurring the Line Between Client and Server var title = “ Node.JS - Blurring the Line Between Client and Server ”; $(this).attr(“title”, title);

Module System

base64.js

var encoding = 'base64‘ // locals are private exports.toBase64 = function(s) {    return new Buffer(s).toString(encoding)}

app.jsvar b64 = require('./base64') var a = b64.toBase64('JQueryBulgaria')

Page 19: Node.JS - Blurring the Line Between Client and Server var title = “ Node.JS - Blurring the Line Between Client and Server ”; $(this).attr(“title”, title);

Error Handling

• Asynchronous Callbacks and Exceptions• Dude, where is my stack?• Cannot debug across event loop iterations

• Async callback error code convention• First callback parameter is error object

fs.readFile(path, function(err, file) { if (err) { // handle error } //...})

Page 20: Node.JS - Blurring the Line Between Client and Server var title = “ Node.JS - Blurring the Line Between Client and Server ”; $(this).attr(“title”, title);

“Do, or do not. There is no try.”

• Reconsider the conventional wisdom of exception handling• Exceptions are cleaner, more elegant and…

wrong

• Hidden control flow and Corrupt State• Just because you don’t see a code path doesn’t

mean it doesn’t exist

• New generation of languages shun exceptions (like Go)

Page 21: Node.JS - Blurring the Line Between Client and Server var title = “ Node.JS - Blurring the Line Between Client and Server ”; $(this).attr(“title”, title);

Callback Hell – the Modern GOTO

Page 22: Node.JS - Blurring the Line Between Client and Server var title = “ Node.JS - Blurring the Line Between Client and Server ”; $(this).attr(“title”, title);

Avoiding

The Callback Pyramid of Doom

• Keep it shallow• Name your anonymous functions• Avoid nesting

• Use a functional programming helper module• async, underscore (both server and client)

• Other alternatives• Promises• Fibers

Page 23: Node.JS - Blurring the Line Between Client and Server var title = “ Node.JS - Blurring the Line Between Client and Server ”; $(this).attr(“title”, title);

Web App Frameworks

• Node.JS is powerfulo Full control over HTTP servero But most of the time you’ll use a web

framework

• Web App Frameworks like ExpressJS provide:o Routingo Body parsingo Session and Cookie Managemento Templatingo Static File Server, Logger and many more

Page 24: Node.JS - Blurring the Line Between Client and Server var title = “ Node.JS - Blurring the Line Between Client and Server ”; $(this).attr(“title”, title);

ExpressJS – Hit Countervar express = require('express')var app = express(); app.use(express.cookieParser());app.use(express.cookieSession({secret: "dG9wc2VjcmV0"})); app.use(function(req, res) {    var sess = req.session    sess.hits = sess.hits || 0    sess.hits++     res.json({ visits: sess.hits })}); app.listen(80)

Page 25: Node.JS - Blurring the Line Between Client and Server var title = “ Node.JS - Blurring the Line Between Client and Server ”; $(this).attr(“title”, title);

Questions?

res.setHeader(“Content-Type”, “text/plain”)res.write(“[email protected]\n”)res.end(“Bye!”)

Page 26: Node.JS - Blurring the Line Between Client and Server var title = “ Node.JS - Blurring the Line Between Client and Server ”; $(this).attr(“title”, title);

Thanks to our Sponsors:

Diamond Sponsor:

Gold Sponsors:

Swag Sponsors: Media Partners:

Technological Partners:

Silver Sponsors:

Bronze Partners: