Loading presentation...

Present Remotely

Send the link below via email or IM

Copy

Present to your audience

Start remote presentation

  • Invited audience members will follow you as you navigate and present
  • People invited to a presentation do not need a Prezi account
  • This link expires 10 minutes after you close the presentation
  • A maximum of 30 users can follow your presentation
  • Learn more about this feature in our knowledge base article

Do you really want to delete this prezi?

Neither you, nor the coeditors you shared it with will be able to recover it again.

DeleteCancel

Make your likes visible on Facebook?

Connect your Facebook account to Prezi and let your likes appear on your timeline.
You can change this under Settings & Account at any time.

No, thanks

NodeJS Quick Tour

No description
by

kai liao

on 4 September 2012

Comments (0)

Please log in to add your comment.

Report abuse

Transcript of NodeJS Quick Tour

NodeJS Quick Tour Qingdu @ Ali-Data Overview 2009 ~ NOW
v 0.8.8 Performance from tornado.ioloop import IOLoop
from tornado.web import RequestHandler, Application
class MainHandler(RequestHandler):
def get(self):
self.write("Hello, world")
application = Application([(r"/", MainHandler)])
if __name__ == "__main__":
application.listen(8080)
IOLoop.instance().start() Tornado package main
import (
"http"
"io"
)
func handler(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, "Hello, world")
}
func main() {
http.HandleFunc("/", handler)
http.ListenAndServe(":8080", nil)
} Go Lang private void handleHttpRequest(
ChannelHandlerContext ctx, HttpRequest req) throws Exception {
HttpResponse res = new DefaultHttpResponse(HTTP_1_1, OK);
res.setHeader(CONTENT_TYPE, "text/html; charset=UTF-8");
setContentLength(res, 11);
res.setContent(ChannelBuffers.copiedBuffer(
"hello world",
CharsetUtil.US_ASCII));
sendHttpResponse(ctx, req, res);
} Netty require('http').createServer(function(req, res){
res.end('Hello, World');
}).listen(8080); NodeJS Benchmark CPU8x Intel E5410 @2.33GHz
16GB
RHEL 5.4 (Tikanga)
$ ab -c 30 -n 1000000 $URL Result Tornado Go Netty Node 13,526 7,287 2,967 5,214 100 13,351 7,038 2,966 5,157 30 1000 11,332 6,786 2,967 5,080 5000 7,921 6,912 2,982 5,164 Use Cluster Use Cluster var cluster = require('cluster')
, http = require('http');
var server =
http.createServer(function(req, res) {
res.end('Hello World');
});
cluster(server)
.set('workers', 4)
.use(cluster.stats())
.listen(8080); Result Tornado Go Netty Node Node X4 13,526 14,826 7,287 2,967 5,214 100 13,351 14,332 7,038 2,966 5,157 30 1000 11,332 12,161 6,786 2,967 5,080 5000 7,921 8,287 6,912 2,982 5,164 mutilple core
child_process.fork
communicate via IPC and pass server handles Dig into NodeJS check-in everyday Google V8
Libuv Non-Blocking
Event-Driven
Single-Threaded Node.js is a platform built on Chrome's JavaScript runtime for easily building fast, scalable network applications. Ray Dahl Cross Platform
win, osx, *nix Fast enough for you? Over 3x qps Use native net module Non-blocking fs.readFile(session_data, function(data){
// after read
session.load(data);
}
// do something before file read
accesslog.write(); Single-Threaded setTimeout(function(){
for (var i = 0; i < 10; i++) {
console.log(i);
}
});
setTimeout(function(){
for (var i = 0; i < 10; i++) {
console.log(i+10);
}
}); NodeJS is not REALLY single-threaded. Good simple code
low cost
high performance Bad single core
process crash on error Use Worker (cluster)
uncaughtException
Domain module Node's gole is to provide an easy way to build scalable network programs. String, Buffer & Stream String Pure JavaScript is Unicode friendly but not nice to binary data. Buffer Raw data is stored in instances of the Buffer class. var a = new Buffer(10);
console.log(a, a.toString());
var b = new Buffer('some text');
console.log(b, b.toString()); vs <Buffer 00 00 00 00> '\u0000\u0000\u0000\u0000'
<Buffer 73 6f 6d 65 20 74 65 78 74> 'some text' over 1,000 3rd modules active developer community quick response x32 & x64 interactive mode debug support
gdb like
chrome debug Infact, only JavaScript runtime runs in a single thread. All the other threads are handled by a C level thread pool. It internally handles threading needed to do select/epoll/kqueue handling without the user explicitly having to manage that. vs Google V8's heap size is limited to 1GB. So you can't handle data with more than this limit. When dealing with TCP streams or the file system, it's necessary to handle octet streams. A Buffer is similar to an array of integers but corresponds to a raw memory allocation outside the V8 heap. A Buffer cannot be resized. Stream A stream is an abstract interface implemented by various objects in Node. For example a request to an HTTP server is a stream, as is stdout. Streams are readable, writable, or both. All streams are instances of EventEmitter FS Stream var fs = require('fs'), counter = 0;
var stream = fs.createReadStream(__filename,
{bufferSize:32});
stream.on('open', function(){
console.log('file opened');
}).on('data', function(data){
console.log('chunk' + (++counter), data);
}).on('end', function(){
console.log('EOF');
}); Net Stream var net = require('net');
var clients = [];
net.createServer(function(client) {
client.write('Enter your name:\n');
client.once('data', function(data) {
var username = data.toString().trim();
clients.push(client);
broacast(username + ' Join!\n');
client.on('data', function(data) {
if (data.toString().trim() === 'quit') {
client.end();
broacast(username + ' Quit.');
return;
}
var text = username + ' : ' + data;
broacast(text);
});
});
}).listen(11021); Http Stream var http = require('http');
var options = {
host: 'www.google.com',
port: 80, path: '/'
};
http.get(options, function(res) {
console.log("Got response: "
+ res.statusCode);
res.on('data', function(data) {
console.log(data.toString());
});
}).on('error', function(e) {
console.log("Got error: " + e.message);
}); file opened
chunk1 <Buffer 76 61 72 20 66 73 20 3d ...
chunk2 <Buffer 3d 20 30 3b 0a 76 61 72 ...
chunk3 <Buffer 74 72 65 61 6d 28 5f 5f ...
chunk4 <Buffer 7d 29 3b 0a 73 74 72 65 ...
chunk5 <Buffer 7b 0a 20 20 63 6f 6e 73 ...
chunk6 <Buffer 7d 29 2e 6f 6e 28 27 64 ...
chunk7 <Buffer 63 6f 6e 73 6f 6c 65 2e ...
chunk8 <Buffer 29 2c 20 64 61 74 61 29 ...
chunk9 <Buffer 29 7b 0a 20 20 63 6f 6e ...
EOF function broacast(text) {
console.log(text.trim());
var i = 0, l = clients.length;
for(; i < l; i++) {
var c = clients[i];
c.write(text);
}
}; Stream.pipe() Connects this read stream to destination WriteStream. Incoming data on this stream gets written to destination. process.stdin.resume();

process.stdin.pipe(process.stdout,
{ end: false });

process.stdin.on("end", function() {
process.stdout.write("Goodbye\n"); }); CNodeJS.org CNodejs club trello.com PaintChat Cloud9 loggly TermKit AppJS NodeJS in TAOBAO mofang.taobao.com shu.taobao.com ITier NodeFox iService NodeAppEngine taojob Node Packaged Modules Total Packages: 14,189 339,381 downloads in the last day
2,468,321 downloads in the last week
9,235,564 downloads in the last month Thanks Q&A
Full transcript