SlideShare une entreprise Scribd logo
1  sur  57
Node.js
A Guided Tour


Presenter: C. Aaron Cois, Ph.D.
The web is changing
 It   used to be about consumption
Real-time Interaction
Real-time Interaction
 Real-Time   Games
 Chat
 Stock tickers
 Twitter Feeds
 Collaboration
 Creation


…on a massive scale
What do we need to make it
happen?
 Fast,   persistent I/O
     HTTP wasn’t built for this
     Server’s need to push data to clients
     Polling is slow and inefficient


 Scalability
 Usability
 Maintainability
Outline
 What is Node.js?
 Technology Overview
 How does it work?
 Demo
 Code!
 Deployment and Hosting
What is Node.js?
Node.js
 Node.js
        is an event-driven, server-side
 JavaScript environment
    Based on the V8 JavaScript Engine,
     developed by Google
 Most   importantly, node.js is a
    server-side runtime environment, that
    compiles and executes JavaScript very
     efficiently.
Platforms
 Runs    on OSX, Linux, Windows

 Clickable   installers for:
     Windows
     Mac OSX


 Linux   has apt-get and yum
Why Node?
 Node.js is specifically designed for
  building fast, efficient, scalable network
  applications
 Node uses an event-driven, non-blocking
  I/O model to maximize efficiency
Technology: V8 Engine
   Developed by Google
   Ships with the Google Chrome web browser
   Allows Chrome to run JavaScript code much
    faster
       It does this by compiling the JavaScript directly
        into native machine code
       As opposed to interpreting JavaScript, or
        execute it as bytecode
   What does this mean for us, and for Node.js?
Technology: JavaScript
 JavaScript      is:
    A fully-functional programming language
      Capable of doing anything other traditional
       languages (C++, Java, Ruby, etc) can do
    Has an excellent event model
    Traditionally resigned to the context of the
     web application frontend
      i.e.   running inside a web browser
Technology: JavaScript2
 There’sno reason the JavaScript
 language can’t be used elsewhere (say,
 server-side)
     This is where node.js comes in, executing
      JavaScript efficiently on the server-side
 JavaScript   brings to Node.js:
     Natural event-based programming, ideal
      for client-server applications
     A known language, with low overhead
Who is using Node.js?
How does it work?
The Basic Idea


    I/O is expensive
*http://blog.mixu.net/2011/02/01/understanding-the-node-js-event-loop/
Ways to deal with I/O
 Synchronous
     One requests at a time, first come, first serve


 Fork
     New process for each request


 Threads
     New thread for each request

                         *http://www.nightmare.com/medusa/async_sockets.html
Another Thesis


Thread-per-connection
 is memory-expensive
Traditional Threaded Model
N  worker threads/processes
 Each incoming connection handed
  to a worker
  That   worker is now “in use”, and can
     handle no other connection, even if it is
     waiting on:
      FileI/O
      DB I/O
      Network I/O
      etc
The life of a worker…




     Waiting on   Waiting on   Waiting on DB…
     File I/O…    Network
                  Response…

                        Time
The life of a worker…

                  Blocking Wastes Cycles




     Waiting on        Waiting on          Waiting on DB…
     File I/O…         Network
                       Response…

                           Time
The Other Basic Idea


Writing (Good) Threaded
    Code is DIFFICULT
The life of N workers…


Thread 1



Thread 2



Thread 3



Thread 4


                         Time
The life of N workers…


Thread 1



Thread 2



Thread 3



Thread 4


                         Time
The life of N workers…


Thread 1



Thread 2

            ALL PROCESSES IDLE
Thread 3



Thread 4


                         Time
Even worse…
 If
   all threads are in use, every incoming
  connection is blocked


 Thiscan cause
  massive traffic jams
  on high-throughput
  applications
Is this the only way?



                         There is
                        another…
The Node.js way
   Axiom:
       Multi-Threaded code
         Is difficult to write
         Is difficult to debug
         Sucks up more dev/test/maintenance cycles
         Most often has inefficient performance


   Conclusion:
       Screw it: Write code using a single thread
Single threaded?!?
     Skeptical? I don’t blame you




          But hear me out…
Node.js Event Loop
 Event   Loop (from Wikipedia):
    A “construct that waits for and dispatches
     events or messages in a program”


 Instead
        of performing I/O ourselves, we
 dispatch I/O events to Node’s event loop
    It handles threads, process optimization,
     concurrency, etc
Node.js Event Loop




         DB I/O command to event loop

       Net I/O command to event loop
     File I/O command to event loop


                             Time
Node.js Event Loop




         DB I/O command to event loop

       Net I/O command to event loop
     File I/O command to event loop     Open for
                                        more work!
                             Time
Node.js app code…
 Isrun entirely in a single thread
 Passes I/O requests to the event loop,
  along with callbacks

 Your    code then:
      Goes to sleep
      Uses no system resources
      Will be notified via callback when I/O is
       complete
Callback example


var filename = “test_file.txt”;

fs.open(filename, “w”, function(err, file) {
    if (err) throw err;
});
Callback example
   Filesystem module forwards task to event loop


var file = (“test_file.txt”);

fs.open(file, “w”, function(err, file) {
    if (err) throw err;
});
Callback example
                          Callback is invoked when work is complete




var file = (“test_file.txt”);

fs.open(file, “w”, function(err, file) {
    if (err) throw err;
});
This is not magic
   The    following:


for(i=0; i<5; i++) {
   sleep(1000);
}


   Will
       block the entire Node event loop for 5
    seconds
Node is in charge
 Let   Node.js handle
     Dispatch
     Concurrency
     (most) Async operations

 What    Node doesn’t promise:
     To not block when you tell it to
     Order of execution (e.g. forked parallel
      processes)
Interlude: Modules
Node.js API
   Node provides an API in the form of modules
    (a.k.a. libraries)
       Modules work with event loop to dispatch async
        tasks

   API modules are installed along with Node
       They provide standard application framework
        functionality
         STDIO: console logging, timing, tracing
         File System: File system access
         …etc
A Few Good Modules
   Net           Network socket support

   HTTP          HTTP communication

   File System   File system access

   Crypto        Cryptography

   Streams       STDIO

   Many more…
Node.js Community
 Additionally,
              the Node.js community
 maintains excellent modules to enhance
 the capabilities of Node

 These   modules operate as
     Libraries
     Toolkits
     Frameworks
     …and much more.
Notable Community Modules
 Express              Web App Framework

 Socket.io            Websockets, etc

 Passport/Everyauth   Authentication

 Jade                 HTML Template Engine

 Connect              Middleware collection

 Less                 Simplified CSS
Let’s see some code!
Node Web Server

var http = require('http');


http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello Worldn');
}).listen(1337, '127.0.0.1');
Node TCP Listener
var net = require('net');

var server = net.createServer(function (socket) {
    socket.write('Echo serverrn');
    socket.pipe(socket);
});

server.listen(1337, '127.0.0.1');
Live Demo


http://techfestchat.jit.su


      Hosting courtesy of Nodejitsu
Any .NET Devs in the room?

 Microsoft has been expending a lot of
 effort to make Node a first class
 framework



And now…
A sneak preview!
MS WebMatrix 2
   Open WebMatrix 2
Node.js Deployment and
Hosting
Cloud Hosting
   Heroku
   Microsoft Azure
   Nodejitsu
   Cloud Foundry
   Nodester
   DotCloud
   Appfog
   Joyent (coming soon)
   …
Thanks!
   Feel free to look me up at:

http://www.codehenge.net

I love questions, collaborations, and talking with
people!

   If you are interested in formal Node.js
    learning, I also have a course available at:

http://www.udemy.com/learn-nodejs-by-
example/

Contenu connexe

Tendances

Node js presentation
Node js presentationNode js presentation
Node js presentationmartincabrera
 
Nodejs Event Driven Concurrency for Web Applications
Nodejs Event Driven Concurrency for Web ApplicationsNodejs Event Driven Concurrency for Web Applications
Nodejs Event Driven Concurrency for Web ApplicationsGanesh Iyer
 
Original slides from Ryan Dahl's NodeJs intro talk
Original slides from Ryan Dahl's NodeJs intro talkOriginal slides from Ryan Dahl's NodeJs intro talk
Original slides from Ryan Dahl's NodeJs intro talkAarti Parikh
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applicationsTom Croucher
 
introduction to node.js
introduction to node.jsintroduction to node.js
introduction to node.jsorkaplan
 
Server Side Event Driven Programming
Server Side Event Driven ProgrammingServer Side Event Driven Programming
Server Side Event Driven ProgrammingKamal Hussain
 
Nodejs Explained with Examples
Nodejs Explained with ExamplesNodejs Explained with Examples
Nodejs Explained with ExamplesGabriele Lana
 
Introduction to node.js by jiban
Introduction to node.js by jibanIntroduction to node.js by jiban
Introduction to node.js by jibanJibanananda Sana
 
Node.js Workshop - Sela SDP 2015
Node.js Workshop  - Sela SDP 2015Node.js Workshop  - Sela SDP 2015
Node.js Workshop - Sela SDP 2015Nir Noy
 
NodeJS - Server Side JS
NodeJS - Server Side JS NodeJS - Server Side JS
NodeJS - Server Side JS Ganesh Kondal
 
Node Architecture and Getting Started with Express
Node Architecture and Getting Started with ExpressNode Architecture and Getting Started with Express
Node Architecture and Getting Started with Expressjguerrero999
 
Intro to node and non blocking io
Intro to node and non blocking ioIntro to node and non blocking io
Intro to node and non blocking ioAmy Hua
 
RESTful API In Node Js using Express
RESTful API In Node Js using Express RESTful API In Node Js using Express
RESTful API In Node Js using Express Jeetendra singh
 
Node.js, for architects - OpenSlava 2013
Node.js, for architects - OpenSlava 2013Node.js, for architects - OpenSlava 2013
Node.js, for architects - OpenSlava 2013Oscar Renalias
 
Node.js Explained
Node.js ExplainedNode.js Explained
Node.js ExplainedJeff Kunkle
 

Tendances (20)

Node js presentation
Node js presentationNode js presentation
Node js presentation
 
Nodejs Event Driven Concurrency for Web Applications
Nodejs Event Driven Concurrency for Web ApplicationsNodejs Event Driven Concurrency for Web Applications
Nodejs Event Driven Concurrency for Web Applications
 
Introduction Node.js
Introduction Node.jsIntroduction Node.js
Introduction Node.js
 
JavaScript Event Loop
JavaScript Event LoopJavaScript Event Loop
JavaScript Event Loop
 
Original slides from Ryan Dahl's NodeJs intro talk
Original slides from Ryan Dahl's NodeJs intro talkOriginal slides from Ryan Dahl's NodeJs intro talk
Original slides from Ryan Dahl's NodeJs intro talk
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applications
 
introduction to node.js
introduction to node.jsintroduction to node.js
introduction to node.js
 
Server Side Event Driven Programming
Server Side Event Driven ProgrammingServer Side Event Driven Programming
Server Side Event Driven Programming
 
Nodejs Explained with Examples
Nodejs Explained with ExamplesNodejs Explained with Examples
Nodejs Explained with Examples
 
NodeJS for Beginner
NodeJS for BeginnerNodeJS for Beginner
NodeJS for Beginner
 
Introduction to node.js by jiban
Introduction to node.js by jibanIntroduction to node.js by jiban
Introduction to node.js by jiban
 
Node.js Workshop - Sela SDP 2015
Node.js Workshop  - Sela SDP 2015Node.js Workshop  - Sela SDP 2015
Node.js Workshop - Sela SDP 2015
 
NodeJS - Server Side JS
NodeJS - Server Side JS NodeJS - Server Side JS
NodeJS - Server Side JS
 
Node Architecture and Getting Started with Express
Node Architecture and Getting Started with ExpressNode Architecture and Getting Started with Express
Node Architecture and Getting Started with Express
 
Node ppt
Node pptNode ppt
Node ppt
 
Intro to node and non blocking io
Intro to node and non blocking ioIntro to node and non blocking io
Intro to node and non blocking io
 
RESTful API In Node Js using Express
RESTful API In Node Js using Express RESTful API In Node Js using Express
RESTful API In Node Js using Express
 
Node.js
Node.jsNode.js
Node.js
 
Node.js, for architects - OpenSlava 2013
Node.js, for architects - OpenSlava 2013Node.js, for architects - OpenSlava 2013
Node.js, for architects - OpenSlava 2013
 
Node.js Explained
Node.js ExplainedNode.js Explained
Node.js Explained
 

Similaire à Node.js: A Guided Tour

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
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.jsVikash Singh
 
Introduction to node.js GDD
Introduction to node.js GDDIntroduction to node.js GDD
Introduction to node.js GDDSudar Muthu
 
GeekCampSG - Nodejs , Websockets and Realtime Web
GeekCampSG - Nodejs , Websockets and Realtime WebGeekCampSG - Nodejs , Websockets and Realtime Web
GeekCampSG - Nodejs , Websockets and Realtime WebBhagaban Behera
 
Node.js Enterprise Middleware
Node.js Enterprise MiddlewareNode.js Enterprise Middleware
Node.js Enterprise MiddlewareBehrad Zari
 
Kalp Corporate Node JS Perfect Guide
Kalp Corporate Node JS Perfect GuideKalp Corporate Node JS Perfect Guide
Kalp Corporate Node JS Perfect GuideKalp Corporate
 
Node Session - 1
Node Session - 1Node Session - 1
Node Session - 1Bhavin Shah
 
Developing realtime apps with Drupal and NodeJS
Developing realtime apps with Drupal and NodeJS Developing realtime apps with Drupal and NodeJS
Developing realtime apps with Drupal and NodeJS drupalcampest
 
Node.js introduction
Node.js introductionNode.js introduction
Node.js introductionPrasoon Kumar
 
Introduce about Nodejs - duyetdev.com
Introduce about Nodejs - duyetdev.comIntroduce about Nodejs - duyetdev.com
Introduce about Nodejs - duyetdev.comVan-Duyet Le
 
"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
 
Building Applications With the MEAN Stack
Building Applications With the MEAN StackBuilding Applications With the MEAN Stack
Building Applications With the MEAN StackNir Noy
 
NodeJS guide for beginners
NodeJS guide for beginnersNodeJS guide for beginners
NodeJS guide for beginnersEnoch Joshua
 
Top 30 Node.js interview questions
Top 30 Node.js interview questionsTop 30 Node.js interview questions
Top 30 Node.js interview questionstechievarsity
 

Similaire à Node.js: A Guided Tour (20)

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
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
Proposal
ProposalProposal
Proposal
 
Introduction to node.js GDD
Introduction to node.js GDDIntroduction to node.js GDD
Introduction to node.js GDD
 
Introduction to Node.JS
Introduction to Node.JSIntroduction to Node.JS
Introduction to 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
 
Node js internal
Node js internalNode js internal
Node js internal
 
Node.js Enterprise Middleware
Node.js Enterprise MiddlewareNode.js Enterprise Middleware
Node.js Enterprise Middleware
 
Node js beginner
Node js beginnerNode js beginner
Node js beginner
 
Kalp Corporate Node JS Perfect Guide
Kalp Corporate Node JS Perfect GuideKalp Corporate Node JS Perfect Guide
Kalp Corporate Node JS Perfect Guide
 
Node Session - 1
Node Session - 1Node Session - 1
Node Session - 1
 
Developing realtime apps with Drupal and NodeJS
Developing realtime apps with Drupal and NodeJS Developing realtime apps with Drupal and NodeJS
Developing realtime apps with Drupal and NodeJS
 
Node.js introduction
Node.js introductionNode.js introduction
Node.js introduction
 
Introduce about Nodejs - duyetdev.com
Introduce about Nodejs - duyetdev.comIntroduce about Nodejs - duyetdev.com
Introduce about Nodejs - duyetdev.com
 
Best node js course
Best node js courseBest node js course
Best node js course
 
"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)
 
World of Node.JS
World of Node.JSWorld of Node.JS
World of Node.JS
 
Building Applications With the MEAN Stack
Building Applications With the MEAN StackBuilding Applications With the MEAN Stack
Building Applications With the MEAN Stack
 
NodeJS guide for beginners
NodeJS guide for beginnersNodeJS guide for beginners
NodeJS guide for beginners
 
Top 30 Node.js interview questions
Top 30 Node.js interview questionsTop 30 Node.js interview questions
Top 30 Node.js interview questions
 

Plus de cacois

Devopssecfail
DevopssecfailDevopssecfail
Devopssecfailcacois
 
Machine Learning for Modern Developers
Machine Learning for Modern DevelopersMachine Learning for Modern Developers
Machine Learning for Modern Developerscacois
 
Avoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.jsAvoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.jscacois
 
Hadoop: The elephant in the room
Hadoop: The elephant in the roomHadoop: The elephant in the room
Hadoop: The elephant in the roomcacois
 
High-Volume Data Collection and Real Time Analytics Using Redis
High-Volume Data Collection and Real Time Analytics Using RedisHigh-Volume Data Collection and Real Time Analytics Using Redis
High-Volume Data Collection and Real Time Analytics Using Rediscacois
 
Automate your Development Environments with Vagrant
Automate your Development Environments with VagrantAutomate your Development Environments with Vagrant
Automate your Development Environments with Vagrantcacois
 

Plus de cacois (6)

Devopssecfail
DevopssecfailDevopssecfail
Devopssecfail
 
Machine Learning for Modern Developers
Machine Learning for Modern DevelopersMachine Learning for Modern Developers
Machine Learning for Modern Developers
 
Avoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.jsAvoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.js
 
Hadoop: The elephant in the room
Hadoop: The elephant in the roomHadoop: The elephant in the room
Hadoop: The elephant in the room
 
High-Volume Data Collection and Real Time Analytics Using Redis
High-Volume Data Collection and Real Time Analytics Using RedisHigh-Volume Data Collection and Real Time Analytics Using Redis
High-Volume Data Collection and Real Time Analytics Using Redis
 
Automate your Development Environments with Vagrant
Automate your Development Environments with VagrantAutomate your Development Environments with Vagrant
Automate your Development Environments with Vagrant
 

Dernier

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
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
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
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
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
 
"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
 
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
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
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
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
"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
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
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
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfSeasiaInfotech2
 

Dernier (20)

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)
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
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
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
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
 
"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
 
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
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
"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
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
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
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdf
 

Node.js: A Guided Tour

  • 1. Node.js A Guided Tour Presenter: C. Aaron Cois, Ph.D.
  • 2. The web is changing  It used to be about consumption
  • 4. Real-time Interaction  Real-Time Games  Chat  Stock tickers  Twitter Feeds  Collaboration  Creation …on a massive scale
  • 5. What do we need to make it happen?  Fast, persistent I/O  HTTP wasn’t built for this  Server’s need to push data to clients  Polling is slow and inefficient  Scalability  Usability  Maintainability
  • 6.
  • 7. Outline  What is Node.js?  Technology Overview  How does it work?  Demo  Code!  Deployment and Hosting
  • 9. Node.js  Node.js is an event-driven, server-side JavaScript environment  Based on the V8 JavaScript Engine, developed by Google  Most importantly, node.js is a  server-side runtime environment, that  compiles and executes JavaScript very efficiently.
  • 10. Platforms  Runs on OSX, Linux, Windows  Clickable installers for:  Windows  Mac OSX  Linux has apt-get and yum
  • 11. Why Node?  Node.js is specifically designed for building fast, efficient, scalable network applications  Node uses an event-driven, non-blocking I/O model to maximize efficiency
  • 12. Technology: V8 Engine  Developed by Google  Ships with the Google Chrome web browser  Allows Chrome to run JavaScript code much faster  It does this by compiling the JavaScript directly into native machine code  As opposed to interpreting JavaScript, or execute it as bytecode  What does this mean for us, and for Node.js?
  • 13.
  • 14. Technology: JavaScript  JavaScript is:  A fully-functional programming language  Capable of doing anything other traditional languages (C++, Java, Ruby, etc) can do  Has an excellent event model  Traditionally resigned to the context of the web application frontend  i.e. running inside a web browser
  • 15. Technology: JavaScript2  There’sno reason the JavaScript language can’t be used elsewhere (say, server-side)  This is where node.js comes in, executing JavaScript efficiently on the server-side  JavaScript brings to Node.js:  Natural event-based programming, ideal for client-server applications  A known language, with low overhead
  • 16. Who is using Node.js?
  • 17. How does it work?
  • 18. The Basic Idea I/O is expensive
  • 20. Ways to deal with I/O  Synchronous  One requests at a time, first come, first serve  Fork  New process for each request  Threads  New thread for each request *http://www.nightmare.com/medusa/async_sockets.html
  • 22.
  • 23. Traditional Threaded Model N worker threads/processes  Each incoming connection handed to a worker  That worker is now “in use”, and can handle no other connection, even if it is waiting on:  FileI/O  DB I/O  Network I/O  etc
  • 24. The life of a worker… Waiting on Waiting on Waiting on DB… File I/O… Network Response… Time
  • 25. The life of a worker… Blocking Wastes Cycles Waiting on Waiting on Waiting on DB… File I/O… Network Response… Time
  • 26. The Other Basic Idea Writing (Good) Threaded Code is DIFFICULT
  • 27. The life of N workers… Thread 1 Thread 2 Thread 3 Thread 4 Time
  • 28. The life of N workers… Thread 1 Thread 2 Thread 3 Thread 4 Time
  • 29. The life of N workers… Thread 1 Thread 2 ALL PROCESSES IDLE Thread 3 Thread 4 Time
  • 30. Even worse…  If all threads are in use, every incoming connection is blocked  Thiscan cause massive traffic jams on high-throughput applications
  • 31. Is this the only way? There is another…
  • 32. The Node.js way  Axiom:  Multi-Threaded code  Is difficult to write  Is difficult to debug  Sucks up more dev/test/maintenance cycles  Most often has inefficient performance  Conclusion:  Screw it: Write code using a single thread
  • 33. Single threaded?!? Skeptical? I don’t blame you But hear me out…
  • 34. Node.js Event Loop  Event Loop (from Wikipedia):  A “construct that waits for and dispatches events or messages in a program”  Instead of performing I/O ourselves, we dispatch I/O events to Node’s event loop  It handles threads, process optimization, concurrency, etc
  • 35. Node.js Event Loop DB I/O command to event loop Net I/O command to event loop File I/O command to event loop Time
  • 36. Node.js Event Loop DB I/O command to event loop Net I/O command to event loop File I/O command to event loop Open for more work! Time
  • 37. Node.js app code…  Isrun entirely in a single thread  Passes I/O requests to the event loop, along with callbacks  Your code then:  Goes to sleep  Uses no system resources  Will be notified via callback when I/O is complete
  • 38. Callback example var filename = “test_file.txt”; fs.open(filename, “w”, function(err, file) { if (err) throw err; });
  • 39. Callback example Filesystem module forwards task to event loop var file = (“test_file.txt”); fs.open(file, “w”, function(err, file) { if (err) throw err; });
  • 40. Callback example Callback is invoked when work is complete var file = (“test_file.txt”); fs.open(file, “w”, function(err, file) { if (err) throw err; });
  • 41. This is not magic  The following: for(i=0; i<5; i++) { sleep(1000); }  Will block the entire Node event loop for 5 seconds
  • 42. Node is in charge  Let Node.js handle  Dispatch  Concurrency  (most) Async operations  What Node doesn’t promise:  To not block when you tell it to  Order of execution (e.g. forked parallel processes)
  • 44. Node.js API  Node provides an API in the form of modules (a.k.a. libraries)  Modules work with event loop to dispatch async tasks  API modules are installed along with Node  They provide standard application framework functionality  STDIO: console logging, timing, tracing  File System: File system access  …etc
  • 45. A Few Good Modules  Net Network socket support  HTTP HTTP communication  File System File system access  Crypto Cryptography  Streams STDIO  Many more…
  • 46. Node.js Community  Additionally, the Node.js community maintains excellent modules to enhance the capabilities of Node  These modules operate as  Libraries  Toolkits  Frameworks  …and much more.
  • 47. Notable Community Modules  Express Web App Framework  Socket.io Websockets, etc  Passport/Everyauth Authentication  Jade HTML Template Engine  Connect Middleware collection  Less Simplified CSS
  • 49. Node Web Server var http = require('http'); http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello Worldn'); }).listen(1337, '127.0.0.1');
  • 50. Node TCP Listener var net = require('net'); var server = net.createServer(function (socket) { socket.write('Echo serverrn'); socket.pipe(socket); }); server.listen(1337, '127.0.0.1');
  • 51. Live Demo http://techfestchat.jit.su Hosting courtesy of Nodejitsu
  • 52. Any .NET Devs in the room?  Microsoft has been expending a lot of effort to make Node a first class framework And now…
  • 54. MS WebMatrix 2 Open WebMatrix 2
  • 56. Cloud Hosting  Heroku  Microsoft Azure  Nodejitsu  Cloud Foundry  Nodester  DotCloud  Appfog  Joyent (coming soon)  …
  • 57. Thanks!  Feel free to look me up at: http://www.codehenge.net I love questions, collaborations, and talking with people!  If you are interested in formal Node.js learning, I also have a course available at: http://www.udemy.com/learn-nodejs-by- example/