SlideShare a Scribd company logo
Why

     by 桂林




  桂糊涂@weibo
guilin1981@twitter
About me
2003, Delphi.

2006, Java.

2009, Python.

2010, Node.js.

Author of m on g osk in and st or m js
What is node.js?


         Evented I/O
             for
        V8 JavaScript.
What can node.js do?
What can node.js do?
Node.js as webserver
What can node.js do?
Node.js as webserver
C10k problem
What can node.js do?
Node.js as webserver
C10k problem

Comet
What can node.js do?
Node.js as webserver
C10k problem

Comet

Websocket
What can node.js do?
Node.js as webserver
C10k problem

Comet

Websocket



Node.js as TCP server
What can node.js do?
Node.js as webserver
C10k problem

Comet

Websocket



Node.js as TCP server

Node.js as CLI tools
What can node.js do?
Node.js as webserver
C10k problem

Comet

Websocket



Node.js as TCP server

Node.js as CLI tools

Node.js as GUI tools
Why node.js
Wh y asy n c h r on ou s I O ?
Why asynchronous IO?
IO is the bottle-neck of application.
Why asynchronous IO?
IO is the bottle-neck of application.
 Network IO

 File IO

 Database IO
Blocking socket IO
class ServerThread extends Thread {
  public ServerThread(socket){
    this.socket = socket;
  }
  public void run(){
    BufferedReader reader = new
BufferedReader(this.socket.getInputStream());
    String line;
    while((line = reader.readLine()) != null){ // block here
      // handle line
    }
  }
}
...
ServerSocket serverSocket = new ServerSocket(port);
while (true) {
    Socket s = serverSocket.accept(); // block here
    new ServerThread(s).start();
}
Non-blocking socket IO
net.createServer(function(socket){
  socket.on('data', function(data){
      // handle data
  });
  socket.on('close', function(has_error){
      // handle close
  });
  socket.on('error', function(err){
      // handle error
  });
}).listen(port);
Non-blocking IO vs Blocking IO




nginx(non-blocking) vs apache(blocking)
Node.js IO API
stream

fs

http

net

dns
Why node.js
Why asynchronous IO?

Wh y javasc r ip t ?
Why javascript?
Why javascript?
Why javascript?
Why javascript?
Browsers war improving javascript.
Why javascript?
Browsers war improving javascript.

Javascript is one of the f ast est dynamic programming language.
Why javascript?
Browsers war improving javascript.

Javascript is one of the f ast est dynamic programming language.

Javascript is one of the m ost p op u lar programming language.
Why javascript?
Browsers war improving javascript.

Javascript is one of the f ast est dynamic programming language.

Javascript is one of the m ost p op u lar programming language.

Javascript has c losu r e (anonymoused function).
Why javascript?
Browsers war improving javascript.

Javascript is one of the f ast est dynamic programming language.

Javascript is one of the m ost p op u lar programming language.

Javascript has c losu r e (anonymoused function).

Javascript is cross-platform.
Why node.js
Why asynchronous IO?

Why javascript?

Wh y v8 ?
About v8
About v8
V8 javascript VM is used in Goog le Ch r om e .
About v8
V8 javascript VM is used in Goog le Ch r om e .

V8 team is led by L ar s B ak , one of the leading VM engineers in the
world with 20 years of experience in building VM.
About v8
V8 javascript VM is used in Goog le Ch r om e .

V8 team is led by L ar s B ak , one of the leading VM engineers in the
world with 20 years of experience in building VM.

L ar s B ak was the t ec h n ic al lead behind HotSpot(Sun’s Java VM).
HotSpot improved Java’s performance 2 0 x t im es .

Before HotSpot, L ar s B ak worked on a sm allt alk VM .
How fast v8 is?
Fast Property Access

Dynamic Machine Code Generation

Efficient Garbage Collection
V8 example
The JavaScript code to access property x from a Point object is:
point.x
V8 example
The JavaScript code to access property x from a Point object is:
point.x

In V8, the machine code generated for accessing x is:
# ebx = the point object
cmp [ebx,<hidden class offset>],<cached hidden class>
jne <inline cache miss>
mov eax,[ebx, <cached x offset>]
Why node.js
Why asynchronous IO?

Why javascript?

Why v8?

Wh y t h r ead less?
Why threadless?
Why threadless?
2mb stack per thread
Why threadless?
2mb stack per thread

Dead-locking
Why threadless?
2mb stack per thread

Dead-locking

Thread-safe?
Why threadless?
2mb stack per thread

Dead-locking

Thread-safe?

Thread is design for blocking IO.
Why node.js
Why asynchronous IO?

Why javascript?

Why v8?

Why threadless?

Wh y n od e. js sp ec ial?
Why node.js special?
Pythoner:
Why node.js special?
Pythoner:
 Python is one of the most popular dynamic language too.
Why node.js special?
Pythoner:
 Python is one of the most popular dynamic language too.

 Performance of python is OK.
Why node.js special?
Pythoner:
 Python is one of the most popular dynamic language too.

 Performance of python is OK.

 We have good non-blocking web framework.
Tornado by facebook




Tornado is a non-blocking web server, open-source by facebook.
Hello Tornado
import tornado.ioloop
import tornado.web

class MainHandler(tornado.web.RequestHandler):
    def get(self):
        self.write("Hello, world")

application = tornado.web.Application([
    (r"/", MainHandler),
])

if __name__ == "__main__":
    application.listen(8888)
    tornado.ioloop.IOLoop.instance().start()
Hello Nodejs
var http = require('http');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello Node.jsn');
}).listen(3000, "127.0.0.1");
Tornado with IO
import pymongo
import tornado.web

class Handler(tornado.web.RequestHandler):
    @property
    def db(self):
        if not hasattr(self, '_db'):
            # block here
            self._db = pymongo.Connection(
                host='127.0.0.1', port=27017).test
        return self._db

    def get(self):
        try:
            # block here
            user = self.db.users.find_one({'username':
self.current_user})
            self.render('template', full_name=user['full_name'])
        except:
            raise tornado.web.HTTPError(500)
Tornado with async IO
import asyncmongo
import tornado.web

class Handler(tornado.web.RequestHandler):
    @property
    def db(self):
        if not hasattr(self, '_db'):
            self._db = asyncmongo.Client(pool_id='mydb',
                host='127.0.0.1', port=27017,
                maxcached=10, maxconnections=50, dbname='test')
        return self._db

    @tornado.web.asynchronous
    def get(self):
        self.db.users.find({'username': self.current_user}, limit=1,
callback=self._on_response)

   def _on_response(self, response, error):
       if error:
           raise tornado.web.HTTPError(500)
       self.render('template', full_name=respose['full_name'])
Node.js with IO
Anonymoused function, is very important for Evented IO
var mongo   =   require('mongoskin'),
    http    =   require('http'),
    jade    =   require('jade'),
    db      =   mongo.db('localhost/test');

http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/html'});
  db.users.findOne({'username': req.session.current_user},
function(err, user){
    jade.renderFile('template', {user: user}, function(err, html){
      res.end(html);
    });
  });
}).listen(3000, "127.0.0.1");
What make node.js special?
What make node.js special?
Javascript is special.
What make node.js special?
Javascript is special.

Most of node.js modules are asynchronoused.
What make node.js special?
Javascript is special.

Most of node.js modules are asynchronoused.

It’s easy to write threadless module.
What make node.js special?
Javascript is special.

Most of node.js modules are asynchronoused.

It’s easy to write threadless module.

Node.js community is very active.
How many modules?


2320 modules can be
install via npm
2011, June 07.
Node.js community


What do you think
about node
community?
Arunoda:
Its the freedom followed by tools like github and npm. And everything
is growing fast.
Pau:
People is more open minded than in other programming communities.
There is people coming from ruby, python, c, haskell, java, erlang,
php…
Mikeal Rogers:
People using node.js are building stuff. the project seeks to make the
lives better of people building products.
Mikeal Rogers:
People using node.js are building stuff. the project seeks to make the
lives better of people building products.
My experience with Python and Ruby is that their primary reason for
working on the project is around with a new language and/or vm. the
people who work on “core” don’t build products and probably never
will.
Mikeal Rogers:
People using node.js are building stuff. the project seeks to make the
lives better of people building products.
My experience with Python and Ruby is that their primary reason for
working on the project is around with a new language and/or vm. the
people who work on “core” don’t build products and probably never
will.
Node.js is not a language and it doesn’t write it’s own vm. it’s not
attractive to people who don’t care about building stuff with it.
桂林:
潮不等于装13
桂林:
潮不等于装13 , node.js很酷,也很务实。
Why node.js
Why node.js
Why asynchronous IO?
Never blocking, cpu efficient



Why javascript?
Right and popluar language



Why v8?
Extremely fast VM



Why threadless?
Easy, memory efficient



Why node.js special?
Active and creative community
Thank you

More Related Content

What's hot (20)

KEY
NodeJS
.toster
 
PDF
From YUI3 to K2
kaven yan
 
PDF
JavaScript Library Overview
jeresig
 
PPT
The Theory Of The Dom
kaven yan
 
PDF
How to make Ajax work for you
Simon Willison
 
PDF
How to make Ajax Libraries work for you
Simon Willison
 
PDF
Ajax Security
Joe Walker
 
PDF
HTML5 for the Silverlight Guy
David Padbury
 
PDF
Performance Improvements in Browsers
jeresig
 
PPTX
The State of JavaScript (2015)
Domenic Denicola
 
KEY
Node.js 0.8 features
Nicholas McClay
 
PPT
Javascript and Jquery Best practices
Sultan Khan
 
PDF
Intro to Sail.js
Nicholas McClay
 
PDF
Building Fast, Modern Web Applications with Node.js and CoffeeScript
royaldark
 
PDF
Beyond JVM - YOW! Sydney 2013
Charles Nutter
 
PDF
Even faster django
Gage Tseng
 
PDF
JRuby and Invokedynamic - Japan JUG 2015
Charles Nutter
 
PDF
#NoXML: Eliminating XML in Spring Projects - SpringOne 2GX 2015
Matt Raible
 
PDF
Fast as C: How to Write Really Terrible Java
Charles Nutter
 
PDF
JVM for Dummies - OSCON 2011
Charles Nutter
 
NodeJS
.toster
 
From YUI3 to K2
kaven yan
 
JavaScript Library Overview
jeresig
 
The Theory Of The Dom
kaven yan
 
How to make Ajax work for you
Simon Willison
 
How to make Ajax Libraries work for you
Simon Willison
 
Ajax Security
Joe Walker
 
HTML5 for the Silverlight Guy
David Padbury
 
Performance Improvements in Browsers
jeresig
 
The State of JavaScript (2015)
Domenic Denicola
 
Node.js 0.8 features
Nicholas McClay
 
Javascript and Jquery Best practices
Sultan Khan
 
Intro to Sail.js
Nicholas McClay
 
Building Fast, Modern Web Applications with Node.js and CoffeeScript
royaldark
 
Beyond JVM - YOW! Sydney 2013
Charles Nutter
 
Even faster django
Gage Tseng
 
JRuby and Invokedynamic - Japan JUG 2015
Charles Nutter
 
#NoXML: Eliminating XML in Spring Projects - SpringOne 2GX 2015
Matt Raible
 
Fast as C: How to Write Really Terrible Java
Charles Nutter
 
JVM for Dummies - OSCON 2011
Charles Nutter
 

Viewers also liked (17)

PPT
Web Security Introduction Webserver hacking refers to ...
webhostingguy
 
PPT
Web Fendamentals
Hiren Mistry
 
PDF
Ajax And JSON
Rody Middelkoop
 
PPTX
Turning Marketing Words into a Branded People Experience
Bridge Training and Events
 
PPTX
Nodejs
Bhushan Patil
 
PPTX
Summer training seminar
Govind Singh Mahecha
 
PDF
PHPNW14 - Getting Started With AWS
benwaine
 
PPTX
Basic Website 101
Thomas Salmen
 
ODP
Joomla REST API
Ashwin Date
 
PPT
Pentesting web applications
Satish b
 
KEY
Server side scripting smack down - Node.js vs PHP
Marc Gear
 
PDF
Webservices: connecting Joomla! with other programs.
Herman Peeren
 
PDF
SmokeTests
tech.kartenmacherei
 
PPTX
WebSphere App Server vs JBoss vs WebLogic vs Tomcat
WASdev Community
 
PDF
Client Vs. Server Rendering
David Amend
 
PPTX
WebSphere App Server vs JBoss vs WebLogic vs Tomcat (InterConnect 2016)
Roman Kharkovski
 
PPT
How To Deploy A Cloud Based Webserver in 5 minutes - LAMP
Matt Dunlap
 
Web Security Introduction Webserver hacking refers to ...
webhostingguy
 
Web Fendamentals
Hiren Mistry
 
Ajax And JSON
Rody Middelkoop
 
Turning Marketing Words into a Branded People Experience
Bridge Training and Events
 
Summer training seminar
Govind Singh Mahecha
 
PHPNW14 - Getting Started With AWS
benwaine
 
Basic Website 101
Thomas Salmen
 
Joomla REST API
Ashwin Date
 
Pentesting web applications
Satish b
 
Server side scripting smack down - Node.js vs PHP
Marc Gear
 
Webservices: connecting Joomla! with other programs.
Herman Peeren
 
WebSphere App Server vs JBoss vs WebLogic vs Tomcat
WASdev Community
 
Client Vs. Server Rendering
David Amend
 
WebSphere App Server vs JBoss vs WebLogic vs Tomcat (InterConnect 2016)
Roman Kharkovski
 
How To Deploy A Cloud Based Webserver in 5 minutes - LAMP
Matt Dunlap
 
Ad

Similar to Why Node.js (20)

PPTX
Nodejs
Vinod Kumar Marupu
 
ODP
Introduce about Nodejs - duyetdev.com
Van-Duyet Le
 
PPTX
Node.js Test
Maksym Kovalko
 
PPTX
Introduction to Node.js
Vikash Singh
 
PPTX
Proposal
Constantine Priemski
 
PPTX
An overview of node.js
valuebound
 
PPTX
GeekCampSG - Nodejs , Websockets and Realtime Web
Bhagaban Behera
 
KEY
node.js dao
Vladimir Miguro
 
PPTX
Node js
Fatih Şimşek
 
PPT
18_Node.js.ppt
KhalilSalhi7
 
PDF
Nodejs - A quick tour (v6)
Felix Geisendörfer
 
PDF
Nodejs - A quick tour (v5)
Felix Geisendörfer
 
PPT
18_Node.js.ppt
MaulikShah516542
 
PPTX
Kalp Corporate Node JS Perfect Guide
Kalp Corporate
 
KEY
Getting Started with MongoDB and Node.js
Grant Goodale
 
PDF
Tech io nodejs_20130531_v0.6
Ganesh Kondal
 
PPT
Node js presentation
martincabrera
 
PDF
NodeJS
Predhin Sapru
 
PPT
Node
Manav Prasad
 
PPT
Introduction to node.js aka NodeJS
JITENDRA KUMAR PATEL
 
Introduce about Nodejs - duyetdev.com
Van-Duyet Le
 
Node.js Test
Maksym Kovalko
 
Introduction to Node.js
Vikash Singh
 
An overview of node.js
valuebound
 
GeekCampSG - Nodejs , Websockets and Realtime Web
Bhagaban Behera
 
node.js dao
Vladimir Miguro
 
18_Node.js.ppt
KhalilSalhi7
 
Nodejs - A quick tour (v6)
Felix Geisendörfer
 
Nodejs - A quick tour (v5)
Felix Geisendörfer
 
18_Node.js.ppt
MaulikShah516542
 
Kalp Corporate Node JS Perfect Guide
Kalp Corporate
 
Getting Started with MongoDB and Node.js
Grant Goodale
 
Tech io nodejs_20130531_v0.6
Ganesh Kondal
 
Node js presentation
martincabrera
 
Introduction to node.js aka NodeJS
JITENDRA KUMAR PATEL
 
Ad

Why Node.js

  • 1. Why by 桂林 桂糊涂@weibo guilin1981@twitter
  • 2. About me 2003, Delphi. 2006, Java. 2009, Python. 2010, Node.js. Author of m on g osk in and st or m js
  • 3. What is node.js? Evented I/O for V8 JavaScript.
  • 5. What can node.js do? Node.js as webserver
  • 6. What can node.js do? Node.js as webserver C10k problem
  • 7. What can node.js do? Node.js as webserver C10k problem Comet
  • 8. What can node.js do? Node.js as webserver C10k problem Comet Websocket
  • 9. What can node.js do? Node.js as webserver C10k problem Comet Websocket Node.js as TCP server
  • 10. What can node.js do? Node.js as webserver C10k problem Comet Websocket Node.js as TCP server Node.js as CLI tools
  • 11. What can node.js do? Node.js as webserver C10k problem Comet Websocket Node.js as TCP server Node.js as CLI tools Node.js as GUI tools
  • 12. Why node.js Wh y asy n c h r on ou s I O ?
  • 13. Why asynchronous IO? IO is the bottle-neck of application.
  • 14. Why asynchronous IO? IO is the bottle-neck of application. Network IO File IO Database IO
  • 15. Blocking socket IO class ServerThread extends Thread { public ServerThread(socket){ this.socket = socket; } public void run(){ BufferedReader reader = new BufferedReader(this.socket.getInputStream()); String line; while((line = reader.readLine()) != null){ // block here // handle line } } } ... ServerSocket serverSocket = new ServerSocket(port); while (true) { Socket s = serverSocket.accept(); // block here new ServerThread(s).start(); }
  • 16. Non-blocking socket IO net.createServer(function(socket){ socket.on('data', function(data){ // handle data }); socket.on('close', function(has_error){ // handle close }); socket.on('error', function(err){ // handle error }); }).listen(port);
  • 17. Non-blocking IO vs Blocking IO nginx(non-blocking) vs apache(blocking)
  • 19. Why node.js Why asynchronous IO? Wh y javasc r ip t ?
  • 23. Why javascript? Browsers war improving javascript.
  • 24. Why javascript? Browsers war improving javascript. Javascript is one of the f ast est dynamic programming language.
  • 25. Why javascript? Browsers war improving javascript. Javascript is one of the f ast est dynamic programming language. Javascript is one of the m ost p op u lar programming language.
  • 26. Why javascript? Browsers war improving javascript. Javascript is one of the f ast est dynamic programming language. Javascript is one of the m ost p op u lar programming language. Javascript has c losu r e (anonymoused function).
  • 27. Why javascript? Browsers war improving javascript. Javascript is one of the f ast est dynamic programming language. Javascript is one of the m ost p op u lar programming language. Javascript has c losu r e (anonymoused function). Javascript is cross-platform.
  • 28. Why node.js Why asynchronous IO? Why javascript? Wh y v8 ?
  • 30. About v8 V8 javascript VM is used in Goog le Ch r om e .
  • 31. About v8 V8 javascript VM is used in Goog le Ch r om e . V8 team is led by L ar s B ak , one of the leading VM engineers in the world with 20 years of experience in building VM.
  • 32. About v8 V8 javascript VM is used in Goog le Ch r om e . V8 team is led by L ar s B ak , one of the leading VM engineers in the world with 20 years of experience in building VM. L ar s B ak was the t ec h n ic al lead behind HotSpot(Sun’s Java VM). HotSpot improved Java’s performance 2 0 x t im es . Before HotSpot, L ar s B ak worked on a sm allt alk VM .
  • 33. How fast v8 is? Fast Property Access Dynamic Machine Code Generation Efficient Garbage Collection
  • 34. V8 example The JavaScript code to access property x from a Point object is: point.x
  • 35. V8 example The JavaScript code to access property x from a Point object is: point.x In V8, the machine code generated for accessing x is: # ebx = the point object cmp [ebx,<hidden class offset>],<cached hidden class> jne <inline cache miss> mov eax,[ebx, <cached x offset>]
  • 36. Why node.js Why asynchronous IO? Why javascript? Why v8? Wh y t h r ead less?
  • 39. Why threadless? 2mb stack per thread Dead-locking
  • 40. Why threadless? 2mb stack per thread Dead-locking Thread-safe?
  • 41. Why threadless? 2mb stack per thread Dead-locking Thread-safe? Thread is design for blocking IO.
  • 42. Why node.js Why asynchronous IO? Why javascript? Why v8? Why threadless? Wh y n od e. js sp ec ial?
  • 44. Why node.js special? Pythoner: Python is one of the most popular dynamic language too.
  • 45. Why node.js special? Pythoner: Python is one of the most popular dynamic language too. Performance of python is OK.
  • 46. Why node.js special? Pythoner: Python is one of the most popular dynamic language too. Performance of python is OK. We have good non-blocking web framework.
  • 47. Tornado by facebook Tornado is a non-blocking web server, open-source by facebook.
  • 48. Hello Tornado import tornado.ioloop import tornado.web class MainHandler(tornado.web.RequestHandler): def get(self): self.write("Hello, world") application = tornado.web.Application([ (r"/", MainHandler), ]) if __name__ == "__main__": application.listen(8888) tornado.ioloop.IOLoop.instance().start()
  • 49. Hello Nodejs var http = require('http'); http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello Node.jsn'); }).listen(3000, "127.0.0.1");
  • 50. Tornado with IO import pymongo import tornado.web class Handler(tornado.web.RequestHandler): @property def db(self): if not hasattr(self, '_db'): # block here self._db = pymongo.Connection( host='127.0.0.1', port=27017).test return self._db def get(self): try: # block here user = self.db.users.find_one({'username': self.current_user}) self.render('template', full_name=user['full_name']) except: raise tornado.web.HTTPError(500)
  • 51. Tornado with async IO import asyncmongo import tornado.web class Handler(tornado.web.RequestHandler): @property def db(self): if not hasattr(self, '_db'): self._db = asyncmongo.Client(pool_id='mydb', host='127.0.0.1', port=27017, maxcached=10, maxconnections=50, dbname='test') return self._db @tornado.web.asynchronous def get(self): self.db.users.find({'username': self.current_user}, limit=1, callback=self._on_response) def _on_response(self, response, error): if error: raise tornado.web.HTTPError(500) self.render('template', full_name=respose['full_name'])
  • 52. Node.js with IO Anonymoused function, is very important for Evented IO var mongo = require('mongoskin'), http = require('http'), jade = require('jade'), db = mongo.db('localhost/test'); http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/html'}); db.users.findOne({'username': req.session.current_user}, function(err, user){ jade.renderFile('template', {user: user}, function(err, html){ res.end(html); }); }); }).listen(3000, "127.0.0.1");
  • 53. What make node.js special?
  • 54. What make node.js special? Javascript is special.
  • 55. What make node.js special? Javascript is special. Most of node.js modules are asynchronoused.
  • 56. What make node.js special? Javascript is special. Most of node.js modules are asynchronoused. It’s easy to write threadless module.
  • 57. What make node.js special? Javascript is special. Most of node.js modules are asynchronoused. It’s easy to write threadless module. Node.js community is very active.
  • 58. How many modules? 2320 modules can be install via npm 2011, June 07.
  • 59. Node.js community What do you think about node community?
  • 60. Arunoda: Its the freedom followed by tools like github and npm. And everything is growing fast.
  • 61. Pau: People is more open minded than in other programming communities. There is people coming from ruby, python, c, haskell, java, erlang, php…
  • 62. Mikeal Rogers: People using node.js are building stuff. the project seeks to make the lives better of people building products.
  • 63. Mikeal Rogers: People using node.js are building stuff. the project seeks to make the lives better of people building products. My experience with Python and Ruby is that their primary reason for working on the project is around with a new language and/or vm. the people who work on “core” don’t build products and probably never will.
  • 64. Mikeal Rogers: People using node.js are building stuff. the project seeks to make the lives better of people building products. My experience with Python and Ruby is that their primary reason for working on the project is around with a new language and/or vm. the people who work on “core” don’t build products and probably never will. Node.js is not a language and it doesn’t write it’s own vm. it’s not attractive to people who don’t care about building stuff with it.
  • 68. Why node.js Why asynchronous IO? Never blocking, cpu efficient Why javascript? Right and popluar language Why v8? Extremely fast VM Why threadless? Easy, memory efficient Why node.js special? Active and creative community