3. What is Node.js ?
Created by Ryan Dahl ( Joyent )
Command line tool to run Javascript
Built on Top of Google’s V8 Javascript Engine
Provides Javascript API for Network and File System . Used to
create Servers, Networking tools.
Event-driven , non-blocking I/O APIs
Core written in C/C++ . Supports C/C++ addons.
Can handle thousands of concurrent connections with minimal
overhead on a single process.
7. The Cost of IO
Accessing RAM ~250 CPU cycles
Disk Operations ~41 000 000 CPU cycles
Reading a file
Writing to a file
Network IO ~240 000 000 CPU cycles
Database Query
HTTP Responses
8.
9.
10. Handling I/O
Apache is multithreaded (depending on
conf.)
Spawns a thread per request (or
process)
Each request is in its own "box”
Blocking IO
result = query('SELECT * FROM ...');
print result.id;
11. The Node way
Single thread for your code
...but, I/O runs in parallel
Handle thousands of concurrent connections
with a single process
Need to be very careful with CPU-intensive
code
12. Why JavaScript ?
• Single Threaded , Asynchronous
• Non blocking IO
• Ubiquitous
• Massive codebase of libraries
• One language to rule them all( Full
stack )
15. Our own HTTP Server
var http= require('http');
var s = http.createServer(function(req,res){
res.writeHead(200,{'content-type' : 'text/plain'}) ;
res.end("hello world n");
})
s.listen(8000);
16. Built-in Modules
• File System
require('fs');
• HTTP Client and Server
require('http');
• TCP Sockets
require('net');
• Many more: http://nodejs.org/docs/v0.4.8/api/
17. Express makes HTTP easier
• Node's HTTP module is low level.
• Express is a simple framework inspired by Sinatra
(Ruby).
• InstallingExpress:
npm install express
• Robust verb-based routing
app.get('/about', function(req, res) { });
• Templating(with Jade or EJS)
• Sessions
18. When to use Node.js ?
Realtime Apps
Crawlers
Single-page Apps
Streaming
File uploading
Online Gaming
Collaboration
Live Sports
Live chat
Financial Applications
29. Websockets / Socket.io
Socket.IO aims to make realtime apps possible in every
browser and mobile device, blurring the differences between the
different transport mechanisms. It's care-free realtime 100% in
JavaScript.
30. Show me the code
Visit http://socket.io/#how-to-use for excellent and
simple documentation .