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

GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
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
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
[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
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
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
 
🐬 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
 

Kürzlich hochgeladen (20)

GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
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
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
[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
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
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
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 

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!