Asbjørn Sloth Tønnesen
based on a presentation by:
Paul Barry
What is node.js?
- Written by Ryan Dahl, in 2009 (sponsered by Joyent)
- JavaScript library for building network servers
- Built on V8
- Basically built around one premise...
Why?
var result = db.query("select * from stuff")
- Problem: DB queries take time and this blocks while it executes
- We want to process requests in parallel
- How do we do that?
- THREADS!
Single Threaded Example
require 'socket'
server = TCPServer.new('localhost', 4242)
puts "Sleeper listening on port 4242"
while (session = server.accept)
session << "How long should I sleep for?\n"
session.gets.to_i.downto(1) do |n|
$stdout << "\rSleeping #{n} "
$stdout.flush
sleep 1
end
puts "\r"
session << "Done\n"
session.close
end
Multi-Threaded Example
require 'socket'
server = TCPServer.new('localhost', 4242)
puts "Sleeper listening on port 4242"
while (session = server.accept)
Thread.new do
session << "How long should I sleep for?\n"
session.gets.to_i.downto(1) do |n|
$stdout << "\rSleeping #{n} "
$stdout.flush
sleep 1
end
puts "\r"
session << "Done\n"
session.close
end
end
Maybe Not
- Context switching is not free
- Execution stacks take up memory
- Synchronization
- Deadlocks
- Threads managed by app server
There Is A Better Way
- Event-Driven Programming
- Application runs a main event loop
- Handlers are registered to react to events
- Model used in all modern GUI environments
- Model used already by JavaScript in Web Browsers
A is for Asynchronous
$.get('ajax/test.html', function(data) {
$('.result').html(data)
})
SJAX, a.k.a FAIL-JAX
var data = $.get('sjax/test.html')
$('.result').html(data)
Event-Driven Programming
var el = document.getElementById("foo")
el.addEventListener("click", doSomething)
Code Samples
But does it scale?
- Plurk.com - Twitter-like, Big In Japan
- Over 100K concurrent users, 1B messages
- Ported from Java/JBoss Netty to node.js
- 10 times less memory
- The whole system runs on one box w/ 8 node.js processes
Why use node.js at Veridu
- Security
- Scalability
- Popularity
The End