SlideShare ist ein Scribd-Unternehmen logo
1 von 28
Downloaden Sie, um offline zu lesen
Introduction to
                 Richard Lee
    Taipei Google Technology User Group
console.info(me);
•   Richard Lee

•   iOS / Ruby / JavaScript developer

•   Co-founder of Polydice, Inc.


•   Email: dlackty@gmail.com

•   Twitter: @dlackty
Node.js
•   Event-driven I/O framework

•   Usually known as server-side JavaScript

•   Based on V8 JavaScript Engine by Google

•   Great community supported


•   However, only on Unix-like platforms
Event-driven I/O framework
•   Everything in Node.js is asynchronous

•   Doesn’t have to wait for slow file I/O or database
    operations to continue processing

•   Make it insanely fast

•   Handle millions of concurrent connections at once


•   It’s also known as non-blocking server
Benchmark              100 concurrent clients
                          1 megabyte response




Node.js



 Nginx



   Thin



Mongrel
                                      req/sec

          0   225   450       675               900
A synchronous example
data = readFromDatabase();
printData(data);


doSomethingUnrelated();



•   The program get blocked when read from database

•   Many CPU cycles are wasted
An asynchronous example
readFromDatabase(function(data) {
      printData(data);
});


doSomethingUnrelated();


•   doSomethingUnrelated() get called immediately

•   printData(data) will be called when finish reading

•   Everything runs in parallel
Benchmark II

   Node.js                                        User CPU         System CPU



    Python



       Perl



      PHP


              0            22.5             45              67.5            90

http://blog.famzah.net/2010/07/01/cpp-vs-python-vs-perl-vs-php-
performance-benchmark/
What is not Node.js
•   Node.js is not full stack Web framework

•   No built-in MVC architecture

•   No built-in database support

•   No built-in URL routing system


•   But all these thins can be found from modules
Event-loop basis
•   All your codes run in an ”event-loop”

•   Stop if no event listeners, and event emitters

•   That is,

    •   a loop waits for event

    •   a loop run in single thread

    •   but everything else is asynchronous
EventEmitter
•   EventEmitter is the core component for Node.js

•   Anything related to I/O wrapped with it

•   Your own class usually inherits it
Using EventEmitter
server.on('connection', function (stream) {
  console.log('someone connected!');
});


server.once('connection', function (stream) {
  console.log('Ah, we have our first user!');
});
Create your own emitter
var events = require('events');
var eventEmitter = new events.EventEmitter();


eventEmitter.on('someOccurence', function(message){
      console.log(message);
});


eventEmitter.emit('someOccurence', 'Something
happened!');
Some pitfalls
•   Remember that event-loop is single thread

•   Always handle event efficiently, otherwise

    •   Event callbacks will get queued in order

    •   User response time becomes longer

    •   The connection won’t drop, though
Bad example
ee = new require('events').EventEmitter();


die = false;
ee.on('die', function() { die = true; });


setTimeout(function() { ee.emit('die'); }, 100);
while(!die);


console.log('done'); // never be called
Fix single thread issue
 •   Spawn new thread if needed

 •   The communication is also down by events

 •   Some principle to follow

     •   Use event callbacks

     •   Avoid share states variables

     •   I/O should be handled by built-in function calls
Good, so how?
•   Coding in JavaScript are natively asynchronous

•   Always need to writes callback functions for I/O

•   Organize your codes as

    •   I/O components - In event-loop

    •   Computational components - Spawn workers
Thus, it’s quite common to see
doSomething(data, function(data) {
      doAnotherThing(data, function(response) {
            doYetAnotherThing(data, function() {
              doJustYetAnotherThing(data, function()) {
                    // kinda of crazy
              });
            });
      });
});


doSomethingUnrelated();
HTTP Server
•   Node.js has built-in HTTP server library

•   Low-level design instead of high level abstraction

•   Supports HTTP 1.1

    •   Thus, the network connection will persist
HTTP Hello World example
var http = require('http');


http.createServer(function(request, response) {
  response.writeHead(200, {'Content-Type': 'text/
plain'});
  response.end('Hello Worldn');
}).listen(8124, "127.0.0.1");


console.log('Server running at http://
127.0.0.1:8124/'
HTTP static file server
http.createServer(function(request, response) {
    var uri = url.parse(request.url).pathname;
    var filename = path.join(process.cwd(), uri);


   // Then read file


}).listen(8080);
HTTP static file server (cont’d)
path.exists(filename, function(exists) {
    	f(!exists) {
    i
    	    response.sendHeader(404, {"Content-Type": "text/plain"});
    	    response.write("404 Not Foundn");
    	    response.close();
    	    return;
    	
    }
    	s.readFile(filename, "binary", function(err, file) {
    f
    	    if(err) {
    	    	    response.sendHeader(500, {"Content-Type": "text/plain"});
    	    	    response.write(err + "n");
    	    	    response.close();
    	    	    return;
    	    }
    	    response.sendHeader(200);
    	    response.write(file, "binary");
    	    response.close();
    	);
    }
});
Easy comet example
var http = require('http');
var spawn = require('child_process').spawn;

http.createServer(function(request, response) {
  response.writeHead(200, {'Content-Type': 'text/plain'});
  var child_process = spawn('tail', ['-F', '/var/log/system.log']);

  request.connection.on('end', function() {
    child_process.kill();
  });

  child_process.stdout.on('data', function(data) {
    console.log(data.toString());
    response.write(data);
  });

}).listen(8080);
Long polling example
var http = require("http");
var requests = [];

http.createServer(function(request, response) {
	 // store the response so we can respond later
	 requests.push(response);
}).listen(8000);

setInterval(function() {
	   // respond to each request
	   while (requests.length) {
	   	   response = requests.shift();
	   	   response.writeHead(200, { "Content-Type": "text/plain" });
	   	   response.end("Hello, World!");
	 }
}, 2000);
Great community support
•   Reminds me of Ruby community

•   GitHub project wiki has lots of resources


•   Most of the related projects are on GitHub

•   npm is a package manager for node
Some books under working
•   Node.js Up and Running

•   Mastering Node.js

•   The Node Beginner Book
How to Node?
•   Pick one of the book or tutorials online

•   Do examples of event-driven programming model

•   Start to code your project

•   Got problem? Read the API, and move on


•   Finally, you learn how to node
Thanks for your hearing!

Weitere ähnliche Inhalte

Was ist angesagt?

Presentation: Everything you wanted to know about writing async, high-concurr...
Presentation: Everything you wanted to know about writing async, high-concurr...Presentation: Everything you wanted to know about writing async, high-concurr...
Presentation: Everything you wanted to know about writing async, high-concurr...Baruch Sadogursky
 
Tornado - different Web programming
Tornado - different Web programmingTornado - different Web programming
Tornado - different Web programmingDima Malenko
 
Java script at backend nodejs
Java script at backend   nodejsJava script at backend   nodejs
Java script at backend nodejsAmit Thakkar
 
Comet with node.js and V8
Comet with node.js and V8Comet with node.js and V8
Comet with node.js and V8amix3k
 
A million connections and beyond - Node.js at scale
A million connections and beyond - Node.js at scaleA million connections and beyond - Node.js at scale
A million connections and beyond - Node.js at scaleTom Croucher
 
Node.js Workshop - Sela SDP 2015
Node.js Workshop  - Sela SDP 2015Node.js Workshop  - Sela SDP 2015
Node.js Workshop - Sela SDP 2015Nir Noy
 
Introduction to node.js aka NodeJS
Introduction to node.js aka NodeJSIntroduction to node.js aka NodeJS
Introduction to node.js aka NodeJSJITENDRA KUMAR PATEL
 
Play framework productivity formula
Play framework   productivity formula Play framework   productivity formula
Play framework productivity formula Sorin Chiprian
 
Node.js System: The Approach
Node.js System: The ApproachNode.js System: The Approach
Node.js System: The ApproachHaci Murat Yaman
 
Non-blocking I/O, Event loops and node.js
Non-blocking I/O, Event loops and node.jsNon-blocking I/O, Event loops and node.js
Non-blocking I/O, Event loops and node.jsMarcus Frödin
 
Node js presentation
Node js presentationNode js presentation
Node js presentationmartincabrera
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.jsVikash Singh
 
Bucks County Tech Meetup: node.js introduction
Bucks County Tech Meetup: node.js introductionBucks County Tech Meetup: node.js introduction
Bucks County Tech Meetup: node.js introductiondshkolnikov
 
Node.js, for architects - OpenSlava 2013
Node.js, for architects - OpenSlava 2013Node.js, for architects - OpenSlava 2013
Node.js, for architects - OpenSlava 2013Oscar Renalias
 
Building servers with Node.js
Building servers with Node.jsBuilding servers with Node.js
Building servers with Node.jsConFoo
 
Even faster django
Even faster djangoEven faster django
Even faster djangoGage Tseng
 
NodeJS ecosystem
NodeJS ecosystemNodeJS ecosystem
NodeJS ecosystemYukti Kaura
 

Was ist angesagt? (20)

Presentation: Everything you wanted to know about writing async, high-concurr...
Presentation: Everything you wanted to know about writing async, high-concurr...Presentation: Everything you wanted to know about writing async, high-concurr...
Presentation: Everything you wanted to know about writing async, high-concurr...
 
Tornado - different Web programming
Tornado - different Web programmingTornado - different Web programming
Tornado - different Web programming
 
Java script at backend nodejs
Java script at backend   nodejsJava script at backend   nodejs
Java script at backend nodejs
 
Comet with node.js and V8
Comet with node.js and V8Comet with node.js and V8
Comet with node.js and V8
 
A million connections and beyond - Node.js at scale
A million connections and beyond - Node.js at scaleA million connections and beyond - Node.js at scale
A million connections and beyond - Node.js at scale
 
Node.js Workshop - Sela SDP 2015
Node.js Workshop  - Sela SDP 2015Node.js Workshop  - Sela SDP 2015
Node.js Workshop - Sela SDP 2015
 
Introduction to node.js aka NodeJS
Introduction to node.js aka NodeJSIntroduction to node.js aka NodeJS
Introduction to node.js aka NodeJS
 
Node.js essentials
 Node.js essentials Node.js essentials
Node.js essentials
 
Tornado in Depth
Tornado in DepthTornado in Depth
Tornado in Depth
 
Play framework productivity formula
Play framework   productivity formula Play framework   productivity formula
Play framework productivity formula
 
Node.js System: The Approach
Node.js System: The ApproachNode.js System: The Approach
Node.js System: The Approach
 
Non-blocking I/O, Event loops and node.js
Non-blocking I/O, Event loops and node.jsNon-blocking I/O, Event loops and node.js
Non-blocking I/O, Event loops and node.js
 
Node js presentation
Node js presentationNode js presentation
Node js presentation
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
Introduction Node.js
Introduction Node.jsIntroduction Node.js
Introduction Node.js
 
Bucks County Tech Meetup: node.js introduction
Bucks County Tech Meetup: node.js introductionBucks County Tech Meetup: node.js introduction
Bucks County Tech Meetup: node.js introduction
 
Node.js, for architects - OpenSlava 2013
Node.js, for architects - OpenSlava 2013Node.js, for architects - OpenSlava 2013
Node.js, for architects - OpenSlava 2013
 
Building servers with Node.js
Building servers with Node.jsBuilding servers with Node.js
Building servers with Node.js
 
Even faster django
Even faster djangoEven faster django
Even faster django
 
NodeJS ecosystem
NodeJS ecosystemNodeJS ecosystem
NodeJS ecosystem
 

Ähnlich wie Introduction to Node.js

introduction to node.js
introduction to node.jsintroduction to node.js
introduction to node.jsorkaplan
 
Node.js: The What, The How and The When
Node.js: The What, The How and The WhenNode.js: The What, The How and The When
Node.js: The What, The How and The WhenFITC
 
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
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applicationsTom Croucher
 
Introduction to NodeJS with LOLCats
Introduction to NodeJS with LOLCatsIntroduction to NodeJS with LOLCats
Introduction to NodeJS with LOLCatsDerek Anderson
 
GeekCampSG - Nodejs , Websockets and Realtime Web
GeekCampSG - Nodejs , Websockets and Realtime WebGeekCampSG - Nodejs , Websockets and Realtime Web
GeekCampSG - Nodejs , Websockets and Realtime WebBhagaban Behera
 
soft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.jssoft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.jssoft-shake.ch
 
A language for the Internet: Why JavaScript and Node.js is right for Internet...
A language for the Internet: Why JavaScript and Node.js is right for Internet...A language for the Internet: Why JavaScript and Node.js is right for Internet...
A language for the Internet: Why JavaScript and Node.js is right for Internet...Tom Croucher
 
Building and Scaling Node.js Applications
Building and Scaling Node.js ApplicationsBuilding and Scaling Node.js Applications
Building and Scaling Node.js ApplicationsOhad Kravchick
 
Intro to node and mongodb 1
Intro to node and mongodb   1Intro to node and mongodb   1
Intro to node and mongodb 1Mohammad Qureshi
 
Node.js introduction
Node.js introductionNode.js introduction
Node.js introductionPrasoon Kumar
 
nodejs_at_a_glance.ppt
nodejs_at_a_glance.pptnodejs_at_a_glance.ppt
nodejs_at_a_glance.pptWalaSidhom1
 
FITC - Node.js 101
FITC - Node.js 101FITC - Node.js 101
FITC - Node.js 101Rami Sayar
 
A language for the Internet: Why JavaScript and Node.js is right for Internet...
A language for the Internet: Why JavaScript and Node.js is right for Internet...A language for the Internet: Why JavaScript and Node.js is right for Internet...
A language for the Internet: Why JavaScript and Node.js is right for Internet...Tom Croucher
 

Ähnlich wie Introduction to Node.js (20)

introduction to node.js
introduction to node.jsintroduction to node.js
introduction to node.js
 
Node.js: The What, The How and The When
Node.js: The What, The How and The WhenNode.js: The What, The How and The When
Node.js: The What, The How and The When
 
Node.js
Node.jsNode.js
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
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applications
 
Introduction to NodeJS with LOLCats
Introduction to NodeJS with LOLCatsIntroduction to NodeJS with LOLCats
Introduction to NodeJS with LOLCats
 
JavaScript Event Loop
JavaScript Event LoopJavaScript Event Loop
JavaScript Event Loop
 
Intro to Node
Intro to NodeIntro to Node
Intro to Node
 
About Node.js
About Node.jsAbout Node.js
About Node.js
 
GeekCampSG - Nodejs , Websockets and Realtime Web
GeekCampSG - Nodejs , Websockets and Realtime WebGeekCampSG - Nodejs , Websockets and Realtime Web
GeekCampSG - Nodejs , Websockets and Realtime Web
 
soft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.jssoft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.js
 
A language for the Internet: Why JavaScript and Node.js is right for Internet...
A language for the Internet: Why JavaScript and Node.js is right for Internet...A language for the Internet: Why JavaScript and Node.js is right for Internet...
A language for the Internet: Why JavaScript and Node.js is right for Internet...
 
Building and Scaling Node.js Applications
Building and Scaling Node.js ApplicationsBuilding and Scaling Node.js Applications
Building and Scaling Node.js Applications
 
Intro to node and mongodb 1
Intro to node and mongodb   1Intro to node and mongodb   1
Intro to node and mongodb 1
 
Node.js introduction
Node.js introductionNode.js introduction
Node.js introduction
 
nodejs_at_a_glance.ppt
nodejs_at_a_glance.pptnodejs_at_a_glance.ppt
nodejs_at_a_glance.ppt
 
FITC - Node.js 101
FITC - Node.js 101FITC - Node.js 101
FITC - Node.js 101
 
What is Node.js
What is Node.jsWhat is Node.js
What is Node.js
 
Nodejs - A quick tour (v6)
Nodejs - A quick tour (v6)Nodejs - A quick tour (v6)
Nodejs - A quick tour (v6)
 
A language for the Internet: Why JavaScript and Node.js is right for Internet...
A language for the Internet: Why JavaScript and Node.js is right for Internet...A language for the Internet: Why JavaScript and Node.js is right for Internet...
A language for the Internet: Why JavaScript and Node.js is right for Internet...
 

Kürzlich hochgeladen

Salesforce Miami User Group Event - 1st Quarter 2024
Salesforce Miami User Group Event - 1st Quarter 2024Salesforce Miami User Group Event - 1st Quarter 2024
Salesforce Miami User Group Event - 1st Quarter 2024SkyPlanner
 
UiPath Studio Web workshop series - Day 7
UiPath Studio Web workshop series - Day 7UiPath Studio Web workshop series - Day 7
UiPath Studio Web workshop series - Day 7DianaGray10
 
PicPay - GenAI Finance Assistant - ChatGPT for Customer Service
PicPay - GenAI Finance Assistant - ChatGPT for Customer ServicePicPay - GenAI Finance Assistant - ChatGPT for Customer Service
PicPay - GenAI Finance Assistant - ChatGPT for Customer ServiceRenan Moreira de Oliveira
 
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...Aggregage
 
AI Fame Rush Review – Virtual Influencer Creation In Just Minutes
AI Fame Rush Review – Virtual Influencer Creation In Just MinutesAI Fame Rush Review – Virtual Influencer Creation In Just Minutes
AI Fame Rush Review – Virtual Influencer Creation In Just MinutesMd Hossain Ali
 
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdfUiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdfDianaGray10
 
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...DianaGray10
 
Do we need a new standard for visualizing the invisible?
Do we need a new standard for visualizing the invisible?Do we need a new standard for visualizing the invisible?
Do we need a new standard for visualizing the invisible?SANGHEE SHIN
 
Introduction to Quantum Computing
Introduction to Quantum ComputingIntroduction to Quantum Computing
Introduction to Quantum ComputingGDSC PJATK
 
GenAI and AI GCC State of AI_Object Automation Inc
GenAI and AI GCC State of AI_Object Automation IncGenAI and AI GCC State of AI_Object Automation Inc
GenAI and AI GCC State of AI_Object Automation IncObject Automation
 
UiPath Community: AI for UiPath Automation Developers
UiPath Community: AI for UiPath Automation DevelopersUiPath Community: AI for UiPath Automation Developers
UiPath Community: AI for UiPath Automation DevelopersUiPathCommunity
 
Cybersecurity Workshop #1.pptx
Cybersecurity Workshop #1.pptxCybersecurity Workshop #1.pptx
Cybersecurity Workshop #1.pptxGDSC PJATK
 
20200723_insight_release_plan_v6.pdf20200723_insight_release_plan_v6.pdf
20200723_insight_release_plan_v6.pdf20200723_insight_release_plan_v6.pdf20200723_insight_release_plan_v6.pdf20200723_insight_release_plan_v6.pdf
20200723_insight_release_plan_v6.pdf20200723_insight_release_plan_v6.pdfJamie (Taka) Wang
 
NIST Cybersecurity Framework (CSF) 2.0 Workshop
NIST Cybersecurity Framework (CSF) 2.0 WorkshopNIST Cybersecurity Framework (CSF) 2.0 Workshop
NIST Cybersecurity Framework (CSF) 2.0 WorkshopBachir Benyammi
 
Nanopower In Semiconductor Industry.pdf
Nanopower  In Semiconductor Industry.pdfNanopower  In Semiconductor Industry.pdf
Nanopower In Semiconductor Industry.pdfPedro Manuel
 
COMPUTER 10 Lesson 8 - Building a Website
COMPUTER 10 Lesson 8 - Building a WebsiteCOMPUTER 10 Lesson 8 - Building a Website
COMPUTER 10 Lesson 8 - Building a Websitedgelyza
 
UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6DianaGray10
 
Crea il tuo assistente AI con lo Stregatto (open source python framework)
Crea il tuo assistente AI con lo Stregatto (open source python framework)Crea il tuo assistente AI con lo Stregatto (open source python framework)
Crea il tuo assistente AI con lo Stregatto (open source python framework)Commit University
 
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve Decarbonization
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve DecarbonizationUsing IESVE for Loads, Sizing and Heat Pump Modeling to Achieve Decarbonization
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve DecarbonizationIES VE
 
Things you didn't know you can use in your Salesforce
Things you didn't know you can use in your SalesforceThings you didn't know you can use in your Salesforce
Things you didn't know you can use in your SalesforceMartin Humpolec
 

Kürzlich hochgeladen (20)

Salesforce Miami User Group Event - 1st Quarter 2024
Salesforce Miami User Group Event - 1st Quarter 2024Salesforce Miami User Group Event - 1st Quarter 2024
Salesforce Miami User Group Event - 1st Quarter 2024
 
UiPath Studio Web workshop series - Day 7
UiPath Studio Web workshop series - Day 7UiPath Studio Web workshop series - Day 7
UiPath Studio Web workshop series - Day 7
 
PicPay - GenAI Finance Assistant - ChatGPT for Customer Service
PicPay - GenAI Finance Assistant - ChatGPT for Customer ServicePicPay - GenAI Finance Assistant - ChatGPT for Customer Service
PicPay - GenAI Finance Assistant - ChatGPT for Customer Service
 
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...
 
AI Fame Rush Review – Virtual Influencer Creation In Just Minutes
AI Fame Rush Review – Virtual Influencer Creation In Just MinutesAI Fame Rush Review – Virtual Influencer Creation In Just Minutes
AI Fame Rush Review – Virtual Influencer Creation In Just Minutes
 
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdfUiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
 
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
 
Do we need a new standard for visualizing the invisible?
Do we need a new standard for visualizing the invisible?Do we need a new standard for visualizing the invisible?
Do we need a new standard for visualizing the invisible?
 
Introduction to Quantum Computing
Introduction to Quantum ComputingIntroduction to Quantum Computing
Introduction to Quantum Computing
 
GenAI and AI GCC State of AI_Object Automation Inc
GenAI and AI GCC State of AI_Object Automation IncGenAI and AI GCC State of AI_Object Automation Inc
GenAI and AI GCC State of AI_Object Automation Inc
 
UiPath Community: AI for UiPath Automation Developers
UiPath Community: AI for UiPath Automation DevelopersUiPath Community: AI for UiPath Automation Developers
UiPath Community: AI for UiPath Automation Developers
 
Cybersecurity Workshop #1.pptx
Cybersecurity Workshop #1.pptxCybersecurity Workshop #1.pptx
Cybersecurity Workshop #1.pptx
 
20200723_insight_release_plan_v6.pdf20200723_insight_release_plan_v6.pdf
20200723_insight_release_plan_v6.pdf20200723_insight_release_plan_v6.pdf20200723_insight_release_plan_v6.pdf20200723_insight_release_plan_v6.pdf
20200723_insight_release_plan_v6.pdf20200723_insight_release_plan_v6.pdf
 
NIST Cybersecurity Framework (CSF) 2.0 Workshop
NIST Cybersecurity Framework (CSF) 2.0 WorkshopNIST Cybersecurity Framework (CSF) 2.0 Workshop
NIST Cybersecurity Framework (CSF) 2.0 Workshop
 
Nanopower In Semiconductor Industry.pdf
Nanopower  In Semiconductor Industry.pdfNanopower  In Semiconductor Industry.pdf
Nanopower In Semiconductor Industry.pdf
 
COMPUTER 10 Lesson 8 - Building a Website
COMPUTER 10 Lesson 8 - Building a WebsiteCOMPUTER 10 Lesson 8 - Building a Website
COMPUTER 10 Lesson 8 - Building a Website
 
UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6
 
Crea il tuo assistente AI con lo Stregatto (open source python framework)
Crea il tuo assistente AI con lo Stregatto (open source python framework)Crea il tuo assistente AI con lo Stregatto (open source python framework)
Crea il tuo assistente AI con lo Stregatto (open source python framework)
 
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve Decarbonization
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve DecarbonizationUsing IESVE for Loads, Sizing and Heat Pump Modeling to Achieve Decarbonization
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve Decarbonization
 
Things you didn't know you can use in your Salesforce
Things you didn't know you can use in your SalesforceThings you didn't know you can use in your Salesforce
Things you didn't know you can use in your Salesforce
 

Introduction to Node.js

  • 1. Introduction to Richard Lee Taipei Google Technology User Group
  • 2. console.info(me); • Richard Lee • iOS / Ruby / JavaScript developer • Co-founder of Polydice, Inc. • Email: dlackty@gmail.com • Twitter: @dlackty
  • 3. Node.js • Event-driven I/O framework • Usually known as server-side JavaScript • Based on V8 JavaScript Engine by Google • Great community supported • However, only on Unix-like platforms
  • 4. Event-driven I/O framework • Everything in Node.js is asynchronous • Doesn’t have to wait for slow file I/O or database operations to continue processing • Make it insanely fast • Handle millions of concurrent connections at once • It’s also known as non-blocking server
  • 5. Benchmark 100 concurrent clients 1 megabyte response Node.js Nginx Thin Mongrel req/sec 0 225 450 675 900
  • 6. A synchronous example data = readFromDatabase(); printData(data); doSomethingUnrelated(); • The program get blocked when read from database • Many CPU cycles are wasted
  • 7. An asynchronous example readFromDatabase(function(data) { printData(data); }); doSomethingUnrelated(); • doSomethingUnrelated() get called immediately • printData(data) will be called when finish reading • Everything runs in parallel
  • 8. Benchmark II Node.js User CPU System CPU Python Perl PHP 0 22.5 45 67.5 90 http://blog.famzah.net/2010/07/01/cpp-vs-python-vs-perl-vs-php- performance-benchmark/
  • 9. What is not Node.js • Node.js is not full stack Web framework • No built-in MVC architecture • No built-in database support • No built-in URL routing system • But all these thins can be found from modules
  • 10. Event-loop basis • All your codes run in an ”event-loop” • Stop if no event listeners, and event emitters • That is, • a loop waits for event • a loop run in single thread • but everything else is asynchronous
  • 11. EventEmitter • EventEmitter is the core component for Node.js • Anything related to I/O wrapped with it • Your own class usually inherits it
  • 12. Using EventEmitter server.on('connection', function (stream) { console.log('someone connected!'); }); server.once('connection', function (stream) { console.log('Ah, we have our first user!'); });
  • 13. Create your own emitter var events = require('events'); var eventEmitter = new events.EventEmitter(); eventEmitter.on('someOccurence', function(message){ console.log(message); }); eventEmitter.emit('someOccurence', 'Something happened!');
  • 14. Some pitfalls • Remember that event-loop is single thread • Always handle event efficiently, otherwise • Event callbacks will get queued in order • User response time becomes longer • The connection won’t drop, though
  • 15. Bad example ee = new require('events').EventEmitter(); die = false; ee.on('die', function() { die = true; }); setTimeout(function() { ee.emit('die'); }, 100); while(!die); console.log('done'); // never be called
  • 16. Fix single thread issue • Spawn new thread if needed • The communication is also down by events • Some principle to follow • Use event callbacks • Avoid share states variables • I/O should be handled by built-in function calls
  • 17. Good, so how? • Coding in JavaScript are natively asynchronous • Always need to writes callback functions for I/O • Organize your codes as • I/O components - In event-loop • Computational components - Spawn workers
  • 18. Thus, it’s quite common to see doSomething(data, function(data) { doAnotherThing(data, function(response) { doYetAnotherThing(data, function() { doJustYetAnotherThing(data, function()) { // kinda of crazy }); }); }); }); doSomethingUnrelated();
  • 19. HTTP Server • Node.js has built-in HTTP server library • Low-level design instead of high level abstraction • Supports HTTP 1.1 • Thus, the network connection will persist
  • 20. HTTP Hello World example var http = require('http'); http.createServer(function(request, response) { response.writeHead(200, {'Content-Type': 'text/ plain'}); response.end('Hello Worldn'); }).listen(8124, "127.0.0.1"); console.log('Server running at http:// 127.0.0.1:8124/'
  • 21. HTTP static file server http.createServer(function(request, response) { var uri = url.parse(request.url).pathname; var filename = path.join(process.cwd(), uri); // Then read file }).listen(8080);
  • 22. HTTP static file server (cont’d) path.exists(filename, function(exists) { f(!exists) { i response.sendHeader(404, {"Content-Type": "text/plain"}); response.write("404 Not Foundn"); response.close(); return; } s.readFile(filename, "binary", function(err, file) { f if(err) { response.sendHeader(500, {"Content-Type": "text/plain"}); response.write(err + "n"); response.close(); return; } response.sendHeader(200); response.write(file, "binary"); response.close(); ); } });
  • 23. Easy comet example var http = require('http'); var spawn = require('child_process').spawn; http.createServer(function(request, response) { response.writeHead(200, {'Content-Type': 'text/plain'}); var child_process = spawn('tail', ['-F', '/var/log/system.log']); request.connection.on('end', function() { child_process.kill(); }); child_process.stdout.on('data', function(data) { console.log(data.toString()); response.write(data); }); }).listen(8080);
  • 24. Long polling example var http = require("http"); var requests = []; http.createServer(function(request, response) { // store the response so we can respond later requests.push(response); }).listen(8000); setInterval(function() { // respond to each request while (requests.length) { response = requests.shift(); response.writeHead(200, { "Content-Type": "text/plain" }); response.end("Hello, World!"); } }, 2000);
  • 25. Great community support • Reminds me of Ruby community • GitHub project wiki has lots of resources • Most of the related projects are on GitHub • npm is a package manager for node
  • 26. Some books under working • Node.js Up and Running • Mastering Node.js • The Node Beginner Book
  • 27. How to Node? • Pick one of the book or tutorials online • Do examples of event-driven programming model • Start to code your project • Got problem? Read the API, and move on • Finally, you learn how to node
  • 28. Thanks for your hearing!