This document discusses server-side event-driven programming using Node.js. It covers how Node.js uses an event loop and asynchronous non-blocking I/O to handle many connections concurrently with high performance. Common Node.js concepts are explained like first-class functions, callbacks, and event emitters. Node.js is compared to traditional threaded programming and shown to have advantages in scalability and efficiency. Example Node.js applications and APIs are provided.
1. Emerging Paradigms -
Server Side Event Driven
Programming
Kamal Hussain
http://www.linkedin.com/in/hussainkamal/
2. Agenda
● Linear Vs Nonlinear Code
● Concurrency through threads and events
● Event loop
● PHP and Javascript
● Node.js - closeup
● Important concepts
3. We are used to ..
val client = new HttpClient()
val method = new GetMethod("http:
//www.google.com")
val statusCode = client.executeMethod
(method)
println("Server responded with %d" .
format(statusCode))
4. Event driven approach
var callback = function(data) {
console.log("firing callback " +
data);
};
$.get('/endpoint', callback);
console.log('Did you see callback?');
5. Achieving scale and concurrency
● Multiple threads/processes
● Size the threadpool correctly
● Each thread is responsible for one task such
as serving a request
● Asynchronous programming
13. Writing synchronous Vs
Asynchronous
// Good: write files asynchronously
fs.writeFile('message.txt', 'Hello Node', function (err) {
console.log("It's saved and the server remains responsive!");
});
// BAD: write files synchronously
fs.writeFileSync('message.txt', 'Hello Node');
console.log("It's saved, but you just blocked ALL requests!");
This can cause performance drop from thousands of requests/seconds to a few
dozen/second.
http://engineering.linkedin.com/nodejs/blazing-fast-nodejs-10-performance-tips-
linkedin-mobile
14. Tale of two languages
● PHP was invented in 1994 by Rasmus
Lerdorfas as a replacement for CGI scripts
● PHP was a substitute for single-threaded C
programs
● Brendan Eich developed Javascript in 1995
for a completely different purpose. JS was
designed to run within Netscape Navigator
and was primarily designed to handle
events.
PHP -> eventless, Javascript -> eventful
15. Node.js
● Ryan Dahl invented Node.js in 2009 as a
continuation of Javascript heritage.
● Node.js is modeled after multi-task, multi-
page handling of a web server.
16. What's Node.js?
"Node.js is a server-side software system designed for
writing scalable Internet applications, notably web servers.
Programs are written on the server side in JavaScript,
using event-driven, asynchronous I/O to minimize overhead
and maximize scalability."
- from wikipedia
17. Node.js - asynchronous I/O
● First class functions
● Closures
● Event loop
● Callback counters
CPU intensive tasks are delegated to workers