SlideShare una empresa de Scribd logo
1 de 60
There’s no sleep()
    in Javascript

Introduction to node.js
      twitter.com/jacek_becela
           github.com/ncr
node.js
node.js
• Server-side Javascript runtime
 • Google V8
 • CommonJS modules
node.js
• Server-side Javascript runtime
 • Google V8
 • CommonJS modules
• API for highly concurrent programming
 • All I/O is non-blocking (asynchronous)
 • Achieved using Event Loop
Two approaches to I/O
// blocking I/O + threads
var urls = db.query("select * from urls"); // wait
urls.each(function (url) {
  var page = http.get(url); // wait
  save(page); // wait
});
 
// non-blocking I/O + event loop
db.query("select * from urls", function (urls) {
  urls.each(function (url) {
    http.get(url, function (page) {
      save(page);
    });
  });
});
I/O Costs




http://nodejs.org/jsconf.pdf
I/O Costs

• L1: 3 cycles




         http://nodejs.org/jsconf.pdf
I/O Costs

• L1: 3 cycles
• L2: 14 cycles



         http://nodejs.org/jsconf.pdf
I/O Costs

• L1: 3 cycles
• L2: 14 cycles
• RAM: 250 cycles


        http://nodejs.org/jsconf.pdf
I/O Costs

• L1: 3 cycles
• L2: 14 cycles
• RAM: 250 cycles
• DISK: 41,000,000 cycles

        http://nodejs.org/jsconf.pdf
I/O Costs

• L1: 3 cycles
• L2: 14 cycles
• RAM: 250 cycles
• DISK: 41,000,000 cycles
• NETWORK: 240,000,000 cycles
       http://nodejs.org/jsconf.pdf
Apache vs. Nginx




http://blog.webfaction.com/a-little-holiday-present
Apache vs. Nginx




http://blog.webfaction.com/a-little-holiday-present
Why threads are bad
Why threads are bad
• Hard to program
Why threads are bad
• Hard to program
• Shared state and locks
Why threads are bad
• Hard to program
• Shared state and locks
• Deadlocks
Why threads are bad
• Hard to program
• Shared state and locks
• Deadlocks
• Giant locks decrease concurrency
Why threads are bad
• Hard to program
• Shared state and locks
• Deadlocks
• Giant locks decrease concurrency
• Fine-grained locks increase complexity
Why threads are bad
• Hard to program
• Shared state and locks
• Deadlocks
• Giant locks decrease concurrency
• Fine-grained locks increase complexity
• Race conditions
Why threads are bad
• Hard to program
• Shared state and locks
• Deadlocks
• Giant locks decrease concurrency
• Fine-grained locks increase complexity
• Race conditions
• Context switching costs
When threads are good
When threads are good

• Support Multi-core CPUs
When threads are good

• Support Multi-core CPUs
• CPU-heavy work
When threads are good

• Support Multi-core CPUs
• CPU-heavy work
• Little or no shared state
When threads are good

• Support Multi-core CPUs
• CPU-heavy work
• Little or no shared state
• Threads count == CPU cores count
Event Loop
 user perspective
• You already use it everyday for I/O
• You register callbacks for events
• Your callback is eventually fired
      $("a").click(function () {
        console.log("clicked!");
      });
       
      $.ajax(..., function (...) {
        console.log("internets!");
      });
Event Loop
 life cycle
Event Loop
            life cycle
• Initialize empty event loop (just an array)
Event Loop
            life cycle
• Initialize empty event loop (just an array)
• Read and “execute” code
Event Loop
            life cycle
• Initialize empty event loop (just an array)
• Read and “execute” code
 • Execute non-I/O code
Event Loop
            life cycle
• Initialize empty event loop (just an array)
• Read and “execute” code
 • Execute non-I/O code
 • Add every I/O call to the event loop
Event Loop
            life cycle
• Initialize empty event loop (just an array)
• Read and “execute” code
 • Execute non-I/O code
 • Add every I/O call to the event loop
• End of source code reached
Event Loop
            life cycle
• Initialize empty event loop (just an array)
• Read and “execute” code
 • Execute non-I/O code
 • Add every I/O call to the event loop
• End of source code reached
• Event loop starts iterating
Event Loop
            life cycle
• Initialize empty event loop (just an array)
• Read and “execute” code
 • Execute non-I/O code
 • Add every I/O call to the event loop
• End of source code reached
• Event loop starts iterating
• All this happens in a single thread
Event Loop
 life cycle
Event Loop
             life cycle
• Iterate over a list of events and callbacks
Event Loop
             life cycle
• Iterate over a list of events and callbacks
• Perform I/O using non-blocking kernel
  facilities: epoll, kqueue, /dev/poll, select
Event Loop
             life cycle
• Iterate over a list of events and callbacks
• Perform I/O using non-blocking kernel
  facilities: epoll, kqueue, /dev/poll, select
• Event Loop goes to sleep
Event Loop
             life cycle
• Iterate over a list of events and callbacks
• Perform I/O using non-blocking kernel
  facilities: epoll, kqueue, /dev/poll, select
• Event Loop goes to sleep
• Kernel notifies the Event Loop
Event Loop
             life cycle
• Iterate over a list of events and callbacks
• Perform I/O using non-blocking kernel
  facilities: epoll, kqueue, /dev/poll, select
• Event Loop goes to sleep
• Kernel notifies the Event Loop
• Event Loop executes and removes a callback
Event Loop
             life cycle
• Iterate over a list of events and callbacks
• Perform I/O using non-blocking kernel
  facilities: epoll, kqueue, /dev/poll, select
• Event Loop goes to sleep
• Kernel notifies the Event Loop
• Event Loop executes and removes a callback
• Program exits when Event Loop is empty
Event Loop limitations
Event Loop limitations
• Callbacks have to return fast
Event Loop limitations
• Callbacks have to return fast
 • No CPU-heavy stuff
Event Loop limitations
• Callbacks have to return fast
 • No CPU-heavy stuff
• What about multi-core CPUs
Event Loop limitations
• Callbacks have to return fast
 • No CPU-heavy stuff
• What about multi-core CPUs
 • Web Workers using separate processes
Event Loop limitations
• Callbacks have to return fast
 • No CPU-heavy stuff
• What about multi-core CPUs
 • Web Workers using separate processes
 • Can do CPU-heavy stuff
Event Loop limitations
• Callbacks have to return fast
 • No CPU-heavy stuff
• What about multi-core CPUs
 • Web Workers using separate processes
 • Can do CPU-heavy stuff
 • No shared memory - no locks
Event Loop limitations
• Callbacks have to return fast
 • No CPU-heavy stuff
• What about multi-core CPUs
 • Web Workers using separate processes
 • Can do CPU-heavy stuff
 • No shared memory - no locks
 • Communication using message passing
Hello World
var sys = require('sys'),
   http = require('http');
http.createServer(function (req, res) {
  setTimeout(function () {
    res.sendHeader(200, {'Content-Type': 'text/plain'});
    res.write('Hello World');
    res.close();
  }, 2000);
}).listen(8000);
sys.puts('Server running at http://127.0.0.1:8000/');
sleep()
sleep()
• It is a blocking call per definition
sleep()
• It is a blocking call per definition
• Browser JS has no blocking functions
sleep()
• It is a blocking call per definition
• Browser JS has no blocking functions
• Except synchronous AJAX which is
  supposed to be used in “unload” event
sleep()
• It is a blocking call per definition
• Browser JS has no blocking functions
• Except synchronous AJAX which is
  supposed to be used in “unload” event
• You can emulate sleep() using a “while”
  loop and checking wall clock but what’s the
  point...
sleep()
• It is a blocking call per definition
• Browser JS has no blocking functions
• Except synchronous AJAX which is
  supposed to be used in “unload” event
• You can emulate sleep() using a “while”
  loop and checking wall clock but what’s the
  point...
• The real reason: JavaScript exceution and
  Event Loop live in a single thread
Where to go next
• github.com/ry/node
• groups.google.com/group/nodejs
• howtonode.org
• dailyjs.org
• search twitter for node.js
• github.com/ncr/flickr_spy
Demo

Más contenido relacionado

La actualidad más candente

Introduction to Node js
Introduction to Node jsIntroduction to Node js
Introduction to Node jsAkshay Mathur
 
Basic Concept of Node.js & NPM
Basic Concept of Node.js & NPMBasic Concept of Node.js & NPM
Basic Concept of Node.js & NPMBhargav Anadkat
 
Node.js Express
Node.js  ExpressNode.js  Express
Node.js ExpressEyal Vardi
 
Introduction to node.js
Introduction to node.jsIntroduction to node.js
Introduction to node.jsDinesh U
 
What is Node.js | Node.js Tutorial for Beginners | Node.js Modules | Node.js ...
What is Node.js | Node.js Tutorial for Beginners | Node.js Modules | Node.js ...What is Node.js | Node.js Tutorial for Beginners | Node.js Modules | Node.js ...
What is Node.js | Node.js Tutorial for Beginners | Node.js Modules | Node.js ...Edureka!
 
The Basics of MongoDB
The Basics of MongoDBThe Basics of MongoDB
The Basics of MongoDBvaluebound
 
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...Edureka!
 
Low Code Integration with Apache Camel.pdf
Low Code Integration with Apache Camel.pdfLow Code Integration with Apache Camel.pdf
Low Code Integration with Apache Camel.pdfClaus Ibsen
 
Node JS Crash Course
Node JS Crash CourseNode JS Crash Course
Node JS Crash CourseHaim Michael
 
Hibernate Presentation
Hibernate  PresentationHibernate  Presentation
Hibernate Presentationguest11106b
 

La actualidad más candente (20)

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
 
Basic Concept of Node.js & NPM
Basic Concept of Node.js & NPMBasic Concept of Node.js & NPM
Basic Concept of Node.js & NPM
 
Express js
Express jsExpress js
Express js
 
Node.js Express
Node.js  ExpressNode.js  Express
Node.js Express
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
Introduction to node.js
Introduction to node.jsIntroduction to node.js
Introduction to node.js
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
What is Node.js | Node.js Tutorial for Beginners | Node.js Modules | Node.js ...
What is Node.js | Node.js Tutorial for Beginners | Node.js Modules | Node.js ...What is Node.js | Node.js Tutorial for Beginners | Node.js Modules | Node.js ...
What is Node.js | Node.js Tutorial for Beginners | Node.js Modules | Node.js ...
 
Express JS
Express JSExpress JS
Express JS
 
The Basics of MongoDB
The Basics of MongoDBThe Basics of MongoDB
The Basics of MongoDB
 
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
 
Introduction to spring boot
Introduction to spring bootIntroduction to spring boot
Introduction to spring boot
 
Introduction to NodeJS
Introduction to NodeJSIntroduction to NodeJS
Introduction to NodeJS
 
Low Code Integration with Apache Camel.pdf
Low Code Integration with Apache Camel.pdfLow Code Integration with Apache Camel.pdf
Low Code Integration with Apache Camel.pdf
 
Restful web services ppt
Restful web services pptRestful web services ppt
Restful web services ppt
 
Node JS Crash Course
Node JS Crash CourseNode JS Crash Course
Node JS Crash Course
 
Hibernate Presentation
Hibernate  PresentationHibernate  Presentation
Hibernate Presentation
 
03 hive query language (hql)
03 hive query language (hql)03 hive query language (hql)
03 hive query language (hql)
 
Node.js Express Framework
Node.js Express FrameworkNode.js Express Framework
Node.js Express Framework
 

Similar a Introduction to node.js

Basic Understanding and Implement of Node.js
Basic Understanding and Implement of Node.jsBasic Understanding and Implement of Node.js
Basic Understanding and Implement of Node.jsGary Yeh
 
"You Don't Know NODE.JS" by Hengki Mardongan Sihombing (Urbanhire)
"You Don't Know NODE.JS" by Hengki Mardongan Sihombing (Urbanhire)"You Don't Know NODE.JS" by Hengki Mardongan Sihombing (Urbanhire)
"You Don't Know NODE.JS" by Hengki Mardongan Sihombing (Urbanhire)Tech in Asia ID
 
WTF is Twisted?
WTF is Twisted?WTF is Twisted?
WTF is Twisted?hawkowl
 
Oracle WebLogic Diagnostics & Perfomance tuning
Oracle WebLogic Diagnostics & Perfomance tuningOracle WebLogic Diagnostics & Perfomance tuning
Oracle WebLogic Diagnostics & Perfomance tuningMichel Schildmeijer
 
introduction to node.js
introduction to node.jsintroduction to node.js
introduction to node.jsorkaplan
 
C# Async/Await Explained
C# Async/Await ExplainedC# Async/Await Explained
C# Async/Await ExplainedJeremy Likness
 
Web a Quebec - JS Debugging
Web a Quebec - JS DebuggingWeb a Quebec - JS Debugging
Web a Quebec - JS DebuggingRami Sayar
 
Async programming and python
Async programming and pythonAsync programming and python
Async programming and pythonChetan Giridhar
 
[HES2013] Virtually secure, analysis to remote root 0day on an industry leadi...
[HES2013] Virtually secure, analysis to remote root 0day on an industry leadi...[HES2013] Virtually secure, analysis to remote root 0day on an industry leadi...
[HES2013] Virtually secure, analysis to remote root 0day on an industry leadi...Hackito Ergo Sum
 
Introduction to Node.js: What, why and how?
Introduction to Node.js: What, why and how?Introduction to Node.js: What, why and how?
Introduction to Node.js: What, why and how?Christian Joudrey
 
Introduction to ZooKeeper - TriHUG May 22, 2012
Introduction to ZooKeeper - TriHUG May 22, 2012Introduction to ZooKeeper - TriHUG May 22, 2012
Introduction to ZooKeeper - TriHUG May 22, 2012mumrah
 
Node.js introduction
Node.js introductionNode.js introduction
Node.js introductionPrasoon Kumar
 
Dcjq node.js presentation
Dcjq node.js presentationDcjq node.js presentation
Dcjq node.js presentationasync_io
 
Clojure Conj 2014 - Paradigms of core.async - Julian Gamble
Clojure Conj 2014 - Paradigms of core.async - Julian GambleClojure Conj 2014 - Paradigms of core.async - Julian Gamble
Clojure Conj 2014 - Paradigms of core.async - Julian GambleJulian Gamble
 

Similar a Introduction to node.js (20)

JS Event Loop
JS Event LoopJS Event Loop
JS Event Loop
 
Basic Understanding and Implement of Node.js
Basic Understanding and Implement of Node.jsBasic Understanding and Implement of Node.js
Basic Understanding and Implement of Node.js
 
"You Don't Know NODE.JS" by Hengki Mardongan Sihombing (Urbanhire)
"You Don't Know NODE.JS" by Hengki Mardongan Sihombing (Urbanhire)"You Don't Know NODE.JS" by Hengki Mardongan Sihombing (Urbanhire)
"You Don't Know NODE.JS" by Hengki Mardongan Sihombing (Urbanhire)
 
WTF is Twisted?
WTF is Twisted?WTF is Twisted?
WTF is Twisted?
 
SDN TEST Suite
SDN TEST SuiteSDN TEST Suite
SDN TEST Suite
 
Oracle WebLogic Diagnostics & Perfomance tuning
Oracle WebLogic Diagnostics & Perfomance tuningOracle WebLogic Diagnostics & Perfomance tuning
Oracle WebLogic Diagnostics & Perfomance tuning
 
introduction to node.js
introduction to node.jsintroduction to node.js
introduction to node.js
 
C# Async/Await Explained
C# Async/Await ExplainedC# Async/Await Explained
C# Async/Await Explained
 
Web a Quebec - JS Debugging
Web a Quebec - JS DebuggingWeb a Quebec - JS Debugging
Web a Quebec - JS Debugging
 
What is Node.js
What is Node.jsWhat is Node.js
What is Node.js
 
Async programming and python
Async programming and pythonAsync programming and python
Async programming and python
 
JavaScript Event Loop
JavaScript Event LoopJavaScript Event Loop
JavaScript Event Loop
 
How do event loops work in Python?
How do event loops work in Python?How do event loops work in Python?
How do event loops work in Python?
 
[HES2013] Virtually secure, analysis to remote root 0day on an industry leadi...
[HES2013] Virtually secure, analysis to remote root 0day on an industry leadi...[HES2013] Virtually secure, analysis to remote root 0day on an industry leadi...
[HES2013] Virtually secure, analysis to remote root 0day on an industry leadi...
 
Introduction to Node.js: What, why and how?
Introduction to Node.js: What, why and how?Introduction to Node.js: What, why and how?
Introduction to Node.js: What, why and how?
 
Introduction to ZooKeeper - TriHUG May 22, 2012
Introduction to ZooKeeper - TriHUG May 22, 2012Introduction to ZooKeeper - TriHUG May 22, 2012
Introduction to ZooKeeper - TriHUG May 22, 2012
 
Node.js introduction
Node.js introductionNode.js introduction
Node.js introduction
 
Dcjq node.js presentation
Dcjq node.js presentationDcjq node.js presentation
Dcjq node.js presentation
 
Clojure Conj 2014 - Paradigms of core.async - Julian Gamble
Clojure Conj 2014 - Paradigms of core.async - Julian GambleClojure Conj 2014 - Paradigms of core.async - Julian Gamble
Clojure Conj 2014 - Paradigms of core.async - Julian Gamble
 
Node.js
Node.jsNode.js
Node.js
 

Último

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
 
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
 
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
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdfChristopherTHyatt
 
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
 
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
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
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
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
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
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
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
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
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: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 

Último (20)

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
 
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
 
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
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdf
 
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
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
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
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
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
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
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
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
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: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 

Introduction to node.js

  • 1. There’s no sleep() in Javascript Introduction to node.js twitter.com/jacek_becela github.com/ncr
  • 3. node.js • Server-side Javascript runtime • Google V8 • CommonJS modules
  • 4. node.js • Server-side Javascript runtime • Google V8 • CommonJS modules • API for highly concurrent programming • All I/O is non-blocking (asynchronous) • Achieved using Event Loop
  • 5. Two approaches to I/O // blocking I/O + threads var urls = db.query("select * from urls"); // wait urls.each(function (url) {   var page = http.get(url); // wait   save(page); // wait });   // non-blocking I/O + event loop db.query("select * from urls", function (urls) {   urls.each(function (url) {     http.get(url, function (page) {       save(page);     });   }); });
  • 7. I/O Costs • L1: 3 cycles http://nodejs.org/jsconf.pdf
  • 8. I/O Costs • L1: 3 cycles • L2: 14 cycles http://nodejs.org/jsconf.pdf
  • 9. I/O Costs • L1: 3 cycles • L2: 14 cycles • RAM: 250 cycles http://nodejs.org/jsconf.pdf
  • 10. I/O Costs • L1: 3 cycles • L2: 14 cycles • RAM: 250 cycles • DISK: 41,000,000 cycles http://nodejs.org/jsconf.pdf
  • 11. I/O Costs • L1: 3 cycles • L2: 14 cycles • RAM: 250 cycles • DISK: 41,000,000 cycles • NETWORK: 240,000,000 cycles http://nodejs.org/jsconf.pdf
  • 15. Why threads are bad • Hard to program
  • 16. Why threads are bad • Hard to program • Shared state and locks
  • 17. Why threads are bad • Hard to program • Shared state and locks • Deadlocks
  • 18. Why threads are bad • Hard to program • Shared state and locks • Deadlocks • Giant locks decrease concurrency
  • 19. Why threads are bad • Hard to program • Shared state and locks • Deadlocks • Giant locks decrease concurrency • Fine-grained locks increase complexity
  • 20. Why threads are bad • Hard to program • Shared state and locks • Deadlocks • Giant locks decrease concurrency • Fine-grained locks increase complexity • Race conditions
  • 21. Why threads are bad • Hard to program • Shared state and locks • Deadlocks • Giant locks decrease concurrency • Fine-grained locks increase complexity • Race conditions • Context switching costs
  • 23. When threads are good • Support Multi-core CPUs
  • 24. When threads are good • Support Multi-core CPUs • CPU-heavy work
  • 25. When threads are good • Support Multi-core CPUs • CPU-heavy work • Little or no shared state
  • 26. When threads are good • Support Multi-core CPUs • CPU-heavy work • Little or no shared state • Threads count == CPU cores count
  • 27. Event Loop user perspective • You already use it everyday for I/O • You register callbacks for events • Your callback is eventually fired $("a").click(function () {   console.log("clicked!"); });   $.ajax(..., function (...) {   console.log("internets!"); });
  • 29. Event Loop life cycle • Initialize empty event loop (just an array)
  • 30. Event Loop life cycle • Initialize empty event loop (just an array) • Read and “execute” code
  • 31. Event Loop life cycle • Initialize empty event loop (just an array) • Read and “execute” code • Execute non-I/O code
  • 32. Event Loop life cycle • Initialize empty event loop (just an array) • Read and “execute” code • Execute non-I/O code • Add every I/O call to the event loop
  • 33. Event Loop life cycle • Initialize empty event loop (just an array) • Read and “execute” code • Execute non-I/O code • Add every I/O call to the event loop • End of source code reached
  • 34. Event Loop life cycle • Initialize empty event loop (just an array) • Read and “execute” code • Execute non-I/O code • Add every I/O call to the event loop • End of source code reached • Event loop starts iterating
  • 35. Event Loop life cycle • Initialize empty event loop (just an array) • Read and “execute” code • Execute non-I/O code • Add every I/O call to the event loop • End of source code reached • Event loop starts iterating • All this happens in a single thread
  • 37. Event Loop life cycle • Iterate over a list of events and callbacks
  • 38. Event Loop life cycle • Iterate over a list of events and callbacks • Perform I/O using non-blocking kernel facilities: epoll, kqueue, /dev/poll, select
  • 39. Event Loop life cycle • Iterate over a list of events and callbacks • Perform I/O using non-blocking kernel facilities: epoll, kqueue, /dev/poll, select • Event Loop goes to sleep
  • 40. Event Loop life cycle • Iterate over a list of events and callbacks • Perform I/O using non-blocking kernel facilities: epoll, kqueue, /dev/poll, select • Event Loop goes to sleep • Kernel notifies the Event Loop
  • 41. Event Loop life cycle • Iterate over a list of events and callbacks • Perform I/O using non-blocking kernel facilities: epoll, kqueue, /dev/poll, select • Event Loop goes to sleep • Kernel notifies the Event Loop • Event Loop executes and removes a callback
  • 42. Event Loop life cycle • Iterate over a list of events and callbacks • Perform I/O using non-blocking kernel facilities: epoll, kqueue, /dev/poll, select • Event Loop goes to sleep • Kernel notifies the Event Loop • Event Loop executes and removes a callback • Program exits when Event Loop is empty
  • 44. Event Loop limitations • Callbacks have to return fast
  • 45. Event Loop limitations • Callbacks have to return fast • No CPU-heavy stuff
  • 46. Event Loop limitations • Callbacks have to return fast • No CPU-heavy stuff • What about multi-core CPUs
  • 47. Event Loop limitations • Callbacks have to return fast • No CPU-heavy stuff • What about multi-core CPUs • Web Workers using separate processes
  • 48. Event Loop limitations • Callbacks have to return fast • No CPU-heavy stuff • What about multi-core CPUs • Web Workers using separate processes • Can do CPU-heavy stuff
  • 49. Event Loop limitations • Callbacks have to return fast • No CPU-heavy stuff • What about multi-core CPUs • Web Workers using separate processes • Can do CPU-heavy stuff • No shared memory - no locks
  • 50. Event Loop limitations • Callbacks have to return fast • No CPU-heavy stuff • What about multi-core CPUs • Web Workers using separate processes • Can do CPU-heavy stuff • No shared memory - no locks • Communication using message passing
  • 51. Hello World var sys = require('sys'),    http = require('http'); http.createServer(function (req, res) {   setTimeout(function () {     res.sendHeader(200, {'Content-Type': 'text/plain'});     res.write('Hello World');     res.close();   }, 2000); }).listen(8000); sys.puts('Server running at http://127.0.0.1:8000/');
  • 53. sleep() • It is a blocking call per definition
  • 54. sleep() • It is a blocking call per definition • Browser JS has no blocking functions
  • 55. sleep() • It is a blocking call per definition • Browser JS has no blocking functions • Except synchronous AJAX which is supposed to be used in “unload” event
  • 56. sleep() • It is a blocking call per definition • Browser JS has no blocking functions • Except synchronous AJAX which is supposed to be used in “unload” event • You can emulate sleep() using a “while” loop and checking wall clock but what’s the point...
  • 57. sleep() • It is a blocking call per definition • Browser JS has no blocking functions • Except synchronous AJAX which is supposed to be used in “unload” event • You can emulate sleep() using a “while” loop and checking wall clock but what’s the point... • The real reason: JavaScript exceution and Event Loop live in a single thread
  • 58. Where to go next • github.com/ry/node • groups.google.com/group/nodejs • howtonode.org • dailyjs.org • search twitter for node.js • github.com/ncr/flickr_spy
  • 59.
  • 60. Demo

Notas del editor