slides - JS(Saturday)

Download Report

Transcript slides - JS(Saturday)

var talk = {
title: "Node.JS”,
subTitle: “What’s All the Fuss About?”
}
Agenda
 Origins
Isn’t server programming a solved problem?
 Inside Node
Async IO and the Evented Model
 Hands on
Let‘s write some code
 The real world
Packages and popular frameworks
ORIGINS
Evolution of Socket Servers
 In the beginning was… CGI
one new process per request
 Worker Pool Model
dispatch requests to a pool of persistent workers
 The C10k problem
10 thousand concurrent connections
The race for high throughput and low latency.
Thread Pool Model
concurrency = # threads (or processes)
thread pool
request queue
thread 1
thread 2
thread 3
thread 4
thread n
responses
Efficiency of a Worker Thread
process results
route, parse request
form db query
parse db result
form web service query
form response
wait…
wait…
wait…
db query
web service
query
log to disk
wait…
wait…
wait…
wait…
wait…
wait…
wait…
wait…
wait…
Relative I/O Latency
CPU cycles
relative
L1 cache
3
next room ~5m
L2 cache
14
across the street ~20m
RAM
250
next block ~400m
disk
41 000 000
Earth circumference
network
240 000 000
distance to the Moon
IS THERE A BETTER WAY?
Asynchronous (non-blocking) I/O
 Initiate I/O operation and return, don’t block
 Perform other tasks instead of idling
 When I/O completes, process result using an
event notification interface
 Popular web servers: nginx and lighttpd
INSIDE NODE
Node.JS in five words
Evented I/O for V8 JavaScript
A Great Networking Tool
Evented Model
user space
internal
thread pool
event
queue
event
loop
single-thread
network
file system
other
I/O done
What is Node.JS made of?
V8
JavaScript VM
node standard library
http(s), net, stream, fs, events, buffer
JS
node bindings
JS / C++
libuv
thread pool
event loop
async I/O
c-ares
async DNS
http_parser
OpenSSL
zlib, etc.
C/C++
HANDS ON
Async Callbacks - Look Familiar?
setTimeout(function() {
console.log("time's up")
}, 1000);
console.log('hello')
while (true) {}
what gets printed now?
Simple Socket Server
var net = require('net')
var server = net.createServer(function(socket) {
socket.write('hello\n')
socket.end()
})
server.listen(9898)
Events –Listeners and Emitters
var server = net.createServer(function(socket) {
socket.on('data', function(data) {
console.log(data.toString())
})
socket.on('end', function() {
console.log('client disconnected')
})
}).listen(9898)
Simple HTTP Server
var http = require('http')
http.createServer(function(req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'})
res.end("hello\n")
}).listen(9090)
How do we read the request body?
Making HTTP Requests
var http = require('http')
var req = http.request({
host: 'jssaturday.com',
path: '/sofia'
}, function(res) {
console.log(res.statusCode)
res.on('data', function(data) {
console.log(data.toString())
})
})
req.end()
Simple HTTP Forwarding Proxy
 How difficult would it be to write a local
forwarding proxy?
Simple HTTP Forwarding Proxy
var http = require('http')
http.createServer(function(req, res) {
req.pipe(http.request({
host: req.headers.host,
path: req.url,
headers: req.headers
}, function(xRes) {
res.writeHead(xRes.statusCode, xRes.headers)
xRes.pipe(res)
}))
}).listen(8080)
Challenges
 Debugging
 why is my stack trace so short
 exception handling
 Non-linear code
 Nesting
 Requires shift of programming paradigm
 Blocks on CPU
 Beware of CPU intensive tasks
 Run multiple nodes or child processes
Benefits
 Async I/O made easy
 Single-thread simplifies synchronization
 One language to rule them all
 Very active community
 Multi-platform
THE REAL WORLD
Modules
base64.js
var encoding = 'base64‘ // locals are private
exports.toBase64 = function(s) {
return new Buffer(s).toString(encoding)
}
app.js
var b64 = require('./base64')
var a = b64.toBase64('JSSaturday')
Node Package Management
 NPM
 install and publish packages
 upgrade, search, versioning
 npmjs.org
 browse popular packages
 publish your own
Node.JS Resources
 nodejs.org
 which version to use?
 Event X: stable (0.8.x, 0.10.x)
 Odd X: unstable (0.9.x, 0.11.x)
 Documentation: nodejs.org/api
 Playing with the command line REPL
 Build from source: github.com/joyent/node
expressjs: web app framework
 Node.JS is powerful
 full control over HTTP server
 but most of the time you’ll use a web framework
 Web app frameworks likes ExpressJS provide





Request Routing
Body and Parameter Parsing
Session and Cookie Management
Templates
Static File Serving, Logger and many more
ExpressJS – hit counter
var 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)
Questions?
res.setHeader(“Content-Type”, “text/plain”)
res.write(“[email protected]\n”)
res.end(“Bye!”)
Expect very soon: SharePoint Saturday!
 Saturday, June 8, 2013
 Same familiar format – 1 day filled with sessions
focused on SharePoint technologies
 Best SharePoint professionals in the region
 Registrations will be open next week (15th)!
 www.SharePointSaturday.eu
Thanks to our Sponsors:
Diamond Sponsor:
Platinum Sponsors:
Gold Sponsors:
Swag Sponsors:
Media Partners: