SlideShare uma empresa Scribd logo
1 de 28
Baixar para ler offline
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!

Mais conteúdo relacionado

Mais procurados

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
 

Mais procurados (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
 

Semelhante a 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
 

Semelhante a 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...
 

Último

🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 

Último (20)

🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 

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!