SlideShare una empresa de Scribd logo
1 de 69
Descargar para leer sin conexión
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

Más contenido relacionado

La actualidad más candente

From YUI3 to K2
From YUI3 to K2From YUI3 to K2
From YUI3 to K2kaven yan
 
JavaScript Library Overview
JavaScript Library OverviewJavaScript Library Overview
JavaScript Library Overviewjeresig
 
The Theory Of The Dom
The Theory Of The DomThe Theory Of The Dom
The Theory Of The Domkaven yan
 
How to make Ajax work for you
How to make Ajax work for youHow to make Ajax work for you
How to make Ajax work for youSimon Willison
 
How to make Ajax Libraries work for you
How to make Ajax Libraries work for youHow to make Ajax Libraries work for you
How to make Ajax Libraries work for youSimon Willison
 
HTML5 for the Silverlight Guy
HTML5 for the Silverlight GuyHTML5 for the Silverlight Guy
HTML5 for the Silverlight GuyDavid Padbury
 
Performance Improvements in Browsers
Performance Improvements in BrowsersPerformance Improvements in Browsers
Performance Improvements in Browsersjeresig
 
The State of JavaScript (2015)
The State of JavaScript (2015)The State of JavaScript (2015)
The State of JavaScript (2015)Domenic Denicola
 
Javascript and Jquery Best practices
Javascript and Jquery Best practicesJavascript and Jquery Best practices
Javascript and Jquery Best practicesSultan Khan
 
Building Fast, Modern Web Applications with Node.js and CoffeeScript
Building Fast, Modern Web Applications with Node.js and CoffeeScriptBuilding Fast, Modern Web Applications with Node.js and CoffeeScript
Building Fast, Modern Web Applications with Node.js and CoffeeScriptroyaldark
 
Beyond JVM - YOW! Sydney 2013
Beyond JVM - YOW! Sydney 2013Beyond JVM - YOW! Sydney 2013
Beyond JVM - YOW! Sydney 2013Charles Nutter
 
Even faster django
Even faster djangoEven faster django
Even faster djangoGage Tseng
 
JRuby and Invokedynamic - Japan JUG 2015
JRuby and Invokedynamic - Japan JUG 2015JRuby and Invokedynamic - Japan JUG 2015
JRuby and Invokedynamic - Japan JUG 2015Charles Nutter
 
#NoXML: Eliminating XML in Spring Projects - SpringOne 2GX 2015
#NoXML: Eliminating XML in Spring Projects - SpringOne 2GX 2015#NoXML: Eliminating XML in Spring Projects - SpringOne 2GX 2015
#NoXML: Eliminating XML in Spring Projects - SpringOne 2GX 2015Matt Raible
 
Fast as C: How to Write Really Terrible Java
Fast as C: How to Write Really Terrible JavaFast as C: How to Write Really Terrible Java
Fast as C: How to Write Really Terrible JavaCharles Nutter
 
JVM for Dummies - OSCON 2011
JVM for Dummies - OSCON 2011JVM for Dummies - OSCON 2011
JVM for Dummies - OSCON 2011Charles Nutter
 

La actualidad más candente (20)

NodeJS
NodeJSNodeJS
NodeJS
 
From YUI3 to K2
From YUI3 to K2From YUI3 to K2
From YUI3 to K2
 
JavaScript Library Overview
JavaScript Library OverviewJavaScript Library Overview
JavaScript Library Overview
 
The Theory Of The Dom
The Theory Of The DomThe Theory Of The Dom
The Theory Of The Dom
 
How to make Ajax work for you
How to make Ajax work for youHow to make Ajax work for you
How to make Ajax work for you
 
How to make Ajax Libraries work for you
How to make Ajax Libraries work for youHow to make Ajax Libraries work for you
How to make Ajax Libraries work for you
 
Ajax Security
Ajax SecurityAjax Security
Ajax Security
 
HTML5 for the Silverlight Guy
HTML5 for the Silverlight GuyHTML5 for the Silverlight Guy
HTML5 for the Silverlight Guy
 
Performance Improvements in Browsers
Performance Improvements in BrowsersPerformance Improvements in Browsers
Performance Improvements in Browsers
 
The State of JavaScript (2015)
The State of JavaScript (2015)The State of JavaScript (2015)
The State of JavaScript (2015)
 
Node.js 0.8 features
Node.js 0.8 featuresNode.js 0.8 features
Node.js 0.8 features
 
Javascript and Jquery Best practices
Javascript and Jquery Best practicesJavascript and Jquery Best practices
Javascript and Jquery Best practices
 
Intro to Sail.js
Intro to Sail.jsIntro to Sail.js
Intro to Sail.js
 
Building Fast, Modern Web Applications with Node.js and CoffeeScript
Building Fast, Modern Web Applications with Node.js and CoffeeScriptBuilding Fast, Modern Web Applications with Node.js and CoffeeScript
Building Fast, Modern Web Applications with Node.js and CoffeeScript
 
Beyond JVM - YOW! Sydney 2013
Beyond JVM - YOW! Sydney 2013Beyond JVM - YOW! Sydney 2013
Beyond JVM - YOW! Sydney 2013
 
Even faster django
Even faster djangoEven faster django
Even faster django
 
JRuby and Invokedynamic - Japan JUG 2015
JRuby and Invokedynamic - Japan JUG 2015JRuby and Invokedynamic - Japan JUG 2015
JRuby and Invokedynamic - Japan JUG 2015
 
#NoXML: Eliminating XML in Spring Projects - SpringOne 2GX 2015
#NoXML: Eliminating XML in Spring Projects - SpringOne 2GX 2015#NoXML: Eliminating XML in Spring Projects - SpringOne 2GX 2015
#NoXML: Eliminating XML in Spring Projects - SpringOne 2GX 2015
 
Fast as C: How to Write Really Terrible Java
Fast as C: How to Write Really Terrible JavaFast as C: How to Write Really Terrible Java
Fast as C: How to Write Really Terrible Java
 
JVM for Dummies - OSCON 2011
JVM for Dummies - OSCON 2011JVM for Dummies - OSCON 2011
JVM for Dummies - OSCON 2011
 

Destacado

Web Security Introduction Webserver hacking refers to ...
Web Security Introduction Webserver hacking refers to ...Web Security Introduction Webserver hacking refers to ...
Web Security Introduction Webserver hacking refers to ...webhostingguy
 
Turning Marketing Words into a Branded People Experience
Turning Marketing Words into a Branded People ExperienceTurning Marketing Words into a Branded People Experience
Turning Marketing Words into a Branded People ExperienceBridge Training and Events
 
PHPNW14 - Getting Started With AWS
PHPNW14 - Getting Started With AWSPHPNW14 - Getting Started With AWS
PHPNW14 - Getting Started With AWSbenwaine
 
Pentesting web applications
Pentesting web applicationsPentesting web applications
Pentesting web applicationsSatish b
 
Server side scripting smack down - Node.js vs PHP
Server side scripting smack down - Node.js vs PHPServer side scripting smack down - Node.js vs PHP
Server side scripting smack down - Node.js vs PHPMarc Gear
 
Webservices: connecting Joomla! with other programs.
Webservices: connecting Joomla! with other programs.Webservices: connecting Joomla! with other programs.
Webservices: connecting Joomla! with other programs.Herman Peeren
 
WebSphere App Server vs JBoss vs WebLogic vs Tomcat
WebSphere App Server vs JBoss vs WebLogic vs TomcatWebSphere App Server vs JBoss vs WebLogic vs Tomcat
WebSphere App Server vs JBoss vs WebLogic vs TomcatWASdev Community
 
Client Vs. Server Rendering
Client Vs. Server RenderingClient Vs. Server Rendering
Client Vs. Server RenderingDavid Amend
 
WebSphere App Server vs JBoss vs WebLogic vs Tomcat (InterConnect 2016)
WebSphere App Server vs JBoss vs WebLogic vs Tomcat (InterConnect 2016)WebSphere App Server vs JBoss vs WebLogic vs Tomcat (InterConnect 2016)
WebSphere App Server vs JBoss vs WebLogic vs Tomcat (InterConnect 2016)Roman Kharkovski
 
How To Deploy A Cloud Based Webserver in 5 minutes - LAMP
How To Deploy A Cloud Based Webserver in 5 minutes - LAMPHow To Deploy A Cloud Based Webserver in 5 minutes - LAMP
How To Deploy A Cloud Based Webserver in 5 minutes - LAMPMatt Dunlap
 

Destacado (17)

Web Security Introduction Webserver hacking refers to ...
Web Security Introduction Webserver hacking refers to ...Web Security Introduction Webserver hacking refers to ...
Web Security Introduction Webserver hacking refers to ...
 
Web Fendamentals
Web FendamentalsWeb Fendamentals
Web Fendamentals
 
Ajax And JSON
Ajax And JSONAjax And JSON
Ajax And JSON
 
Turning Marketing Words into a Branded People Experience
Turning Marketing Words into a Branded People ExperienceTurning Marketing Words into a Branded People Experience
Turning Marketing Words into a Branded People Experience
 
Nodejs
NodejsNodejs
Nodejs
 
Summer training seminar
Summer training seminarSummer training seminar
Summer training seminar
 
PHPNW14 - Getting Started With AWS
PHPNW14 - Getting Started With AWSPHPNW14 - Getting Started With AWS
PHPNW14 - Getting Started With AWS
 
Basic Website 101
Basic Website 101Basic Website 101
Basic Website 101
 
Joomla REST API
Joomla REST APIJoomla REST API
Joomla REST API
 
Pentesting web applications
Pentesting web applicationsPentesting web applications
Pentesting web applications
 
Server side scripting smack down - Node.js vs PHP
Server side scripting smack down - Node.js vs PHPServer side scripting smack down - Node.js vs PHP
Server side scripting smack down - Node.js vs PHP
 
Webservices: connecting Joomla! with other programs.
Webservices: connecting Joomla! with other programs.Webservices: connecting Joomla! with other programs.
Webservices: connecting Joomla! with other programs.
 
SmokeTests
SmokeTestsSmokeTests
SmokeTests
 
WebSphere App Server vs JBoss vs WebLogic vs Tomcat
WebSphere App Server vs JBoss vs WebLogic vs TomcatWebSphere App Server vs JBoss vs WebLogic vs Tomcat
WebSphere App Server vs JBoss vs WebLogic vs Tomcat
 
Client Vs. Server Rendering
Client Vs. Server RenderingClient Vs. Server Rendering
Client Vs. Server Rendering
 
WebSphere App Server vs JBoss vs WebLogic vs Tomcat (InterConnect 2016)
WebSphere App Server vs JBoss vs WebLogic vs Tomcat (InterConnect 2016)WebSphere App Server vs JBoss vs WebLogic vs Tomcat (InterConnect 2016)
WebSphere App Server vs JBoss vs WebLogic vs Tomcat (InterConnect 2016)
 
How To Deploy A Cloud Based Webserver in 5 minutes - LAMP
How To Deploy A Cloud Based Webserver in 5 minutes - LAMPHow To Deploy A Cloud Based Webserver in 5 minutes - LAMP
How To Deploy A Cloud Based Webserver in 5 minutes - LAMP
 

Similar a Why Node.js

Developing realtime apps with Drupal and NodeJS
Developing realtime apps with Drupal and NodeJS Developing realtime apps with Drupal and NodeJS
Developing realtime apps with Drupal and NodeJS drupalcampest
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.jsVikash Singh
 
node.js: Javascript's in your backend
node.js: Javascript's in your backendnode.js: Javascript's in your backend
node.js: Javascript's in your backendDavid Padbury
 
Node.js introduction
Node.js introductionNode.js introduction
Node.js introductionParth Joshi
 
Practical Use of MongoDB for Node.js
Practical Use of MongoDB for Node.jsPractical Use of MongoDB for Node.js
Practical Use of MongoDB for Node.jsasync_io
 
Event-driven IO server-side JavaScript environment based on V8 Engine
Event-driven IO server-side JavaScript environment based on V8 EngineEvent-driven IO server-side JavaScript environment based on V8 Engine
Event-driven IO server-side JavaScript environment based on V8 EngineRicardo Silva
 
OSCON 2011 - Node.js Tutorial
OSCON 2011 - Node.js TutorialOSCON 2011 - Node.js Tutorial
OSCON 2011 - Node.js TutorialTom Croucher
 
Original slides from Ryan Dahl's NodeJs intro talk
Original slides from Ryan Dahl's NodeJs intro talkOriginal slides from Ryan Dahl's NodeJs intro talk
Original slides from Ryan Dahl's NodeJs intro talkAarti Parikh
 
GeekCampSG - Nodejs , Websockets and Realtime Web
GeekCampSG - Nodejs , Websockets and Realtime WebGeekCampSG - Nodejs , Websockets and Realtime Web
GeekCampSG - Nodejs , Websockets and Realtime WebBhagaban Behera
 
JavaScript Libraries: The Big Picture
JavaScript Libraries: The Big PictureJavaScript Libraries: The Big Picture
JavaScript Libraries: The Big PictureSimon Willison
 
Modern server side development with node.js - Benjamin gruenbaum
Modern server side development with node.js - Benjamin gruenbaumModern server side development with node.js - Benjamin gruenbaum
Modern server side development with node.js - Benjamin gruenbaumgeektimecoil
 
Ruby on Rails survival guide of an aged Java developer
Ruby on Rails survival guide of an aged Java developerRuby on Rails survival guide of an aged Java developer
Ruby on Rails survival guide of an aged Java developergicappa
 

Similar a Why Node.js (20)

Developing realtime apps with Drupal and NodeJS
Developing realtime apps with Drupal and NodeJS Developing realtime apps with Drupal and NodeJS
Developing realtime apps with Drupal and NodeJS
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
node.js: Javascript's in your backend
node.js: Javascript's in your backendnode.js: Javascript's in your backend
node.js: Javascript's in your backend
 
Node azure
Node azureNode azure
Node azure
 
Node.JS briefly introduced
Node.JS briefly introducedNode.JS briefly introduced
Node.JS briefly introduced
 
Node.js introduction
Node.js introductionNode.js introduction
Node.js introduction
 
Practical Use of MongoDB for Node.js
Practical Use of MongoDB for Node.jsPractical Use of MongoDB for Node.js
Practical Use of MongoDB for Node.js
 
Node js
Node jsNode js
Node js
 
hacking with node.JS
hacking with node.JShacking with node.JS
hacking with node.JS
 
Event-driven IO server-side JavaScript environment based on V8 Engine
Event-driven IO server-side JavaScript environment based on V8 EngineEvent-driven IO server-side JavaScript environment based on V8 Engine
Event-driven IO server-side JavaScript environment based on V8 Engine
 
Node.js vs Play Framework
Node.js vs Play FrameworkNode.js vs Play Framework
Node.js vs Play Framework
 
NodeJS
NodeJSNodeJS
NodeJS
 
Node.js 1, 2, 3
Node.js 1, 2, 3Node.js 1, 2, 3
Node.js 1, 2, 3
 
OSCON 2011 - Node.js Tutorial
OSCON 2011 - Node.js TutorialOSCON 2011 - Node.js Tutorial
OSCON 2011 - Node.js Tutorial
 
Original slides from Ryan Dahl's NodeJs intro talk
Original slides from Ryan Dahl's NodeJs intro talkOriginal slides from Ryan Dahl's NodeJs intro talk
Original slides from Ryan Dahl's NodeJs intro talk
 
GeekCampSG - Nodejs , Websockets and Realtime Web
GeekCampSG - Nodejs , Websockets and Realtime WebGeekCampSG - Nodejs , Websockets and Realtime Web
GeekCampSG - Nodejs , Websockets and Realtime Web
 
JavaScript Libraries: The Big Picture
JavaScript Libraries: The Big PictureJavaScript Libraries: The Big Picture
JavaScript Libraries: The Big Picture
 
Modern server side development with node.js - Benjamin gruenbaum
Modern server side development with node.js - Benjamin gruenbaumModern server side development with node.js - Benjamin gruenbaum
Modern server side development with node.js - Benjamin gruenbaum
 
Proposal
ProposalProposal
Proposal
 
Ruby on Rails survival guide of an aged Java developer
Ruby on Rails survival guide of an aged Java developerRuby on Rails survival guide of an aged Java developer
Ruby on Rails survival guide of an aged Java developer
 

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