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

DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 

Último (20)

DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 

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!