SlideShare une entreprise Scribd logo
1  sur  30
Introduction to node.js

End to end web development w/
           javascript


                  Or Kaplan
                  kaplanor@gmail.com
What is node?
       Taking JS Beyond the Browser

Node.js is a framework for building scalable
  server-side applications and network
  oriented programs with asynchronous
                 javascript.
External
  modules



Node modules
 (fs,tcp http)



Node internals




  Google V8
Full JavaScript Stack




•   meteor.com
Before we start
• JavaScript JavaScript JavaScript
Hello world example
setTimeout(function () {
    console.log("world");
}, 2000);

console.log("hello");

setInterval(function () {
    console.log("world");
}, 2000);

console.log("hello");
The non-blocking notion
•   Single threaded
•   Instead of waiting use events
•   Never wait for IO (socket, disk etc.)
•   JS is natural for building async programs
•   For blocking operation the node internals
    uses thread pool to wait for operations to
    finish.
Traditional I/O

var data = file.read('file.txt');
process(data);
Traditional I/O

var data = file.read('file.txt');
ZzZzZZZzz…
process(data);




             Why wasting those cycles?!
Non-Blocking I/O
file.read('file.txt', function (data) {
    process(data);
    return success;
});


DoWhateverYouWishMeanwhile();
Node Modules




The true force of node
NPM
• NPM is a package manager for node.js
  – http://npmjs.org/
Express Package
• RESTful module for node webapps
• Supports cookies, sessions, caching etc.
• www.expressjs.com
Example of Express API
var Express = require('express'),
     app = Express.createServer();

app.get('/users/(:user)/?', function (req, res) {
       res.send('hello ' + req.params.user);
});

app.listen(process.env.PORT || process.argv[3] || 8080);
Comet Use Case
• Comet is a way for the client to get a real
  time event from the server
• How would you implement?
  – Polling – using AJAX to poll for events for
    events
  – Long Polling – Send HTTP requests in
    chain, the response is delayed.
  – Streaming – Keep open socket to the server.
Requirements
• Comet servers need to maintain many
  open connections
• Holding one thread per connection is
  unacceptable
• Node.js approach is better – easier to
  scale, less resources per connection.
Implementing using web sockets
• Introduced on HTML5
• Creating a thin layer over TCP/IP accepting
  constrain of the web
• Supported by node.js
• On this Demo we will use the socket.io
  module, which is HTML4 compatible web
  socket
Chat Demo
              Chat server in less than 40 lines of code




https://gist.github.com/4542595
Buffering vs. Streaming
Exec – buffering (callback)
var util = require('util'),
     exec = require('child_process').exec,
     child;

child = exec('cat *.js bad_file | wc -l',
   function (error, stdout, stderr) {
       console.log('stdout: ' + stdout);
       console.log('stderr: ' + stderr);
       if (error !== null) {
           console.log('exec error: ' + error);
       }
  });
Spawn - streaming
var util = require('util'),
    spawn = require('child_process').spawn,
    ls = spawn('ls', ['-lh', '/usr']);

ls.stdout.on('data', function (data) {
     console.log('stdout: ' + data);
});

ls.stderr.on('data', function (data) {
     console.log('stderr: ' + data);
});

ls.on('exit', function (code) {
     console.log('child process exited with code ' + code)
;
});
Live Site Tips
•   Test your code
•   Run static analysis
•   Monitor your app
•   Let it scale
•   Continuous deployment
•   Use process manager- SMF, forever or upstart
•   Document your code
•   Share code between client and server
•   Explore the community
•   Global uncaught exception handler
•   Chaos monkey
Why should one use node.js
•   You already code your client using JS
•   Great Performance- http://four.livejournal.com/1019177.html
•   Can support thousands of concurrent connections
•   Easy to scale
•   Ideal for the mobile era
•   Fast development
•   Easy debug
•   No locks - V8 uses only one thread!
•   Community
Good For
•   Small-Medium projects
•   Prototyping
•   Fast scale servers
•   Flexible dynamic application (inject code)
•   Web sockets
Limitations
• New programming style
• Using only one thread
• Immature environment
• Limited stack trace
• A bug may crash the whole server – use
  forever watch dog.
• Dynamic language – what’s your religion?
Some Patterns
• Always return values on last statement
• Pass callbacks
• Code is not linear avoid infinite
  indentation (extract callback into named
  functions)
• Promises
• Test using node unit – high coverage is
  crucial
Debugging (V8)
• Builtin debugger-
  http://nodejs.org/docs/v0.5.9/api/debugger.html
• Ndb - https://github.com/smtlaissezfaire/ndb
• Inspector – web based (webkit) debugger -
  https://github.com/dannycoates/node-inspector
• Web storm - http://www.jetbrains.com/webstorm/
• Eclipse -
  https://github.com/joyent/node/wiki/Using-
  Eclipse-as-Node-Applications-Debugger
CoffeeScript
• A ruby like scripting language that compiles to JavaScript.




• Quick guide - http://jashkenas.github.com/coffee-script/
• Great slides at http://bodil.github.com/coffeescript/
References
•   Node.js – http://www.nodejs.org
•   Comet - http://amix.dk/blog/post/19577
•   Comet - http://www.slideshare.net/amix3k/comet-with-nodejs-and-v8
•   WebSockets - http://howtonode.org/websockets-socketio
•   Best Practices - http://stella.laurenzo.org/2011/03/bulletproof-node-js-
    coding/

• Best Practices - http://howtonode.org
• Node modules - https://github.com/joyent/node/wiki/modules
• Node on Production - http://dshaw.github.com/2012-05-jsday/#/16
Questions?




        Or Kaplan
        kaplanor@gmail.com

Contenu connexe

Tendances

Node js presentation
Node js presentationNode js presentation
Node js presentationmartincabrera
 
Intro to Node.js (v1)
Intro to Node.js (v1)Intro to Node.js (v1)
Intro to Node.js (v1)Chris Cowan
 
Node.js Patterns for Discerning Developers
Node.js Patterns for Discerning DevelopersNode.js Patterns for Discerning Developers
Node.js Patterns for Discerning Developerscacois
 
Node.js and How JavaScript is Changing Server Programming
Node.js and How JavaScript is Changing Server Programming  Node.js and How JavaScript is Changing Server Programming
Node.js and How JavaScript is Changing Server Programming Tom Croucher
 
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
 
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
 
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
 
Server Side Event Driven Programming
Server Side Event Driven ProgrammingServer Side Event Driven Programming
Server Side Event Driven ProgrammingKamal Hussain
 
Node.js Explained
Node.js ExplainedNode.js Explained
Node.js ExplainedJeff Kunkle
 
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
 
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
 
Java script at backend nodejs
Java script at backend   nodejsJava script at backend   nodejs
Java script at backend nodejsAmit Thakkar
 
All aboard the NodeJS Express
All aboard the NodeJS ExpressAll aboard the NodeJS Express
All aboard the NodeJS ExpressDavid Boyer
 
Building your first Node app with Connect & Express
Building your first Node app with Connect & ExpressBuilding your first Node app with Connect & Express
Building your first Node app with Connect & ExpressChristian Joudrey
 

Tendances (20)

Node js presentation
Node js presentationNode js presentation
Node js presentation
 
Intro to Node.js (v1)
Intro to Node.js (v1)Intro to Node.js (v1)
Intro to Node.js (v1)
 
NodeJS for Beginner
NodeJS for BeginnerNodeJS for Beginner
NodeJS for Beginner
 
Node.js Patterns for Discerning Developers
Node.js Patterns for Discerning DevelopersNode.js Patterns for Discerning Developers
Node.js Patterns for Discerning Developers
 
NodeJS
NodeJSNodeJS
NodeJS
 
Node.js and How JavaScript is Changing Server Programming
Node.js and How JavaScript is Changing Server Programming  Node.js and How JavaScript is Changing Server Programming
Node.js and How JavaScript is Changing Server Programming
 
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?
 
Node.js - Best practices
Node.js  - Best practicesNode.js  - Best practices
Node.js - Best practices
 
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
 
NodeJS
NodeJSNodeJS
NodeJS
 
Node ppt
Node pptNode ppt
Node ppt
 
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
 
Server Side Event Driven Programming
Server Side Event Driven ProgrammingServer Side Event Driven Programming
Server Side Event Driven Programming
 
Node.js Explained
Node.js ExplainedNode.js Explained
Node.js Explained
 
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
 
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
 
Java script at backend nodejs
Java script at backend   nodejsJava script at backend   nodejs
Java script at backend nodejs
 
Nodejs in Production
Nodejs in ProductionNodejs in Production
Nodejs in Production
 
All aboard the NodeJS Express
All aboard the NodeJS ExpressAll aboard the NodeJS Express
All aboard the NodeJS Express
 
Building your first Node app with Connect & Express
Building your first Node app with Connect & ExpressBuilding your first Node app with Connect & Express
Building your first Node app with Connect & Express
 

En vedette

EmpireJS: Hacking Art with Node js and Image Analysis
EmpireJS: Hacking Art with Node js and Image AnalysisEmpireJS: Hacking Art with Node js and Image Analysis
EmpireJS: Hacking Art with Node js and Image Analysisjeresig
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.jsVikash Singh
 
From Hello World to Real World - Container Days Boston 2016
From Hello World to Real World - Container Days Boston 2016From Hello World to Real World - Container Days Boston 2016
From Hello World to Real World - Container Days Boston 2016Shannon Williams
 
Node.js ― Hello, world! の1歩先へ。
Node.js ― Hello, world! の1歩先へ。Node.js ― Hello, world! の1歩先へ。
Node.js ― Hello, world! の1歩先へ。Tatsuya Tobioka
 
Angular 2 - The Next Framework
Angular 2 - The Next FrameworkAngular 2 - The Next Framework
Angular 2 - The Next FrameworkCommit University
 
Angular Pipes Workshop
Angular Pipes WorkshopAngular Pipes Workshop
Angular Pipes WorkshopNir Kaufman
 
Introduction to node js - From "hello world" to deploying on azure
Introduction to node js - From "hello world" to deploying on azureIntroduction to node js - From "hello world" to deploying on azure
Introduction to node js - From "hello world" to deploying on azureColin Mackay
 
Introduction to Nodejs
Introduction to NodejsIntroduction to Nodejs
Introduction to NodejsGabriele Lana
 
Redux with angular 2 - workshop 2016
Redux with angular 2 - workshop 2016Redux with angular 2 - workshop 2016
Redux with angular 2 - workshop 2016Nir Kaufman
 
Introduction to Node js
Introduction to Node jsIntroduction to Node js
Introduction to Node jsAkshay Mathur
 
Angular2 workshop
Angular2 workshopAngular2 workshop
Angular2 workshopNir Kaufman
 
Angular 2 - Core Concepts
Angular 2 - Core ConceptsAngular 2 - Core Concepts
Angular 2 - Core ConceptsFabio Biondi
 
Node Foundation Membership Overview 20160907
Node Foundation Membership Overview 20160907Node Foundation Membership Overview 20160907
Node Foundation Membership Overview 20160907NodejsFoundation
 
Introduction to Angular 2
Introduction to Angular 2Introduction to Angular 2
Introduction to Angular 2Knoldus Inc.
 
Building Universal Applications with Angular 2
Building Universal Applications with Angular 2Building Universal Applications with Angular 2
Building Universal Applications with Angular 2Minko Gechev
 

En vedette (20)

EmpireJS: Hacking Art with Node js and Image Analysis
EmpireJS: Hacking Art with Node js and Image AnalysisEmpireJS: Hacking Art with Node js and Image Analysis
EmpireJS: Hacking Art with Node js and Image Analysis
 
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
 
From Hello World to Real World - Container Days Boston 2016
From Hello World to Real World - Container Days Boston 2016From Hello World to Real World - Container Days Boston 2016
From Hello World to Real World - Container Days Boston 2016
 
Nodejs vatsal shah
Nodejs vatsal shahNodejs vatsal shah
Nodejs vatsal shah
 
Node js meetup
Node js meetupNode js meetup
Node js meetup
 
Node.js ― Hello, world! の1歩先へ。
Node.js ― Hello, world! の1歩先へ。Node.js ― Hello, world! の1歩先へ。
Node.js ― Hello, world! の1歩先へ。
 
Angular 2 - The Next Framework
Angular 2 - The Next FrameworkAngular 2 - The Next Framework
Angular 2 - The Next Framework
 
Angular Pipes Workshop
Angular Pipes WorkshopAngular Pipes Workshop
Angular Pipes Workshop
 
Introduction to node js - From "hello world" to deploying on azure
Introduction to node js - From "hello world" to deploying on azureIntroduction to node js - From "hello world" to deploying on azure
Introduction to node js - From "hello world" to deploying on azure
 
Introduction to Nodejs
Introduction to NodejsIntroduction to Nodejs
Introduction to Nodejs
 
Redux with angular 2 - workshop 2016
Redux with angular 2 - workshop 2016Redux with angular 2 - workshop 2016
Redux with angular 2 - workshop 2016
 
Node js for beginners
Node js for beginnersNode js for beginners
Node js for beginners
 
Introduction to Node js
Introduction to Node jsIntroduction to Node js
Introduction to Node js
 
Angular2 workshop
Angular2 workshopAngular2 workshop
Angular2 workshop
 
Angular 2 - Core Concepts
Angular 2 - Core ConceptsAngular 2 - Core Concepts
Angular 2 - Core Concepts
 
Node Foundation Membership Overview 20160907
Node Foundation Membership Overview 20160907Node Foundation Membership Overview 20160907
Node Foundation Membership Overview 20160907
 
Node JS
Node JSNode JS
Node JS
 
Introduction to Angular 2
Introduction to Angular 2Introduction to Angular 2
Introduction to Angular 2
 
Building Universal Applications with Angular 2
Building Universal Applications with Angular 2Building Universal Applications with Angular 2
Building Universal Applications with Angular 2
 

Similaire à Introduction to Node.js: JavaScript Beyond the Browser

"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
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.jsRichard Lee
 
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
 
Nodejs - Should Ruby Developers Care?
Nodejs - Should Ruby Developers Care?Nodejs - Should Ruby Developers Care?
Nodejs - Should Ruby Developers Care?Felix Geisendörfer
 
FITC - Node.js 101
FITC - Node.js 101FITC - Node.js 101
FITC - Node.js 101Rami Sayar
 
Building and Scaling Node.js Applications
Building and Scaling Node.js ApplicationsBuilding and Scaling Node.js Applications
Building and Scaling Node.js ApplicationsOhad Kravchick
 
Nodejs a-practical-introduction-oredev
Nodejs a-practical-introduction-oredevNodejs a-practical-introduction-oredev
Nodejs a-practical-introduction-oredevFelix Geisendörfer
 
What I learned from FluentConf and then some
What I learned from FluentConf and then someWhat I learned from FluentConf and then some
What I learned from FluentConf and then someOhad Kravchick
 
Groovy & Grails eXchange 2012 vert.x presentation
Groovy & Grails eXchange 2012 vert.x presentationGroovy & Grails eXchange 2012 vert.x presentation
Groovy & Grails eXchange 2012 vert.x presentationStuart (Pid) Williams
 
Node.js introduction
Node.js introductionNode.js introduction
Node.js introductionPrasoon Kumar
 
Node.js 101 with Rami Sayar
Node.js 101 with Rami SayarNode.js 101 with Rami Sayar
Node.js 101 with Rami SayarFITC
 
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
 
Intro to node and mongodb 1
Intro to node and mongodb   1Intro to node and mongodb   1
Intro to node and mongodb 1Mohammad Qureshi
 
Practical Use of MongoDB for Node.js
Practical Use of MongoDB for Node.jsPractical Use of MongoDB for Node.js
Practical Use of MongoDB for Node.jsasync_io
 
Intro To Node.js
Intro To Node.jsIntro To Node.js
Intro To Node.jsChris Cowan
 
GeekCampSG - Nodejs , Websockets and Realtime Web
GeekCampSG - Nodejs , Websockets and Realtime WebGeekCampSG - Nodejs , Websockets and Realtime Web
GeekCampSG - Nodejs , Websockets and Realtime WebBhagaban Behera
 

Similaire à Introduction to Node.js: JavaScript Beyond the Browser (20)

JavaScript Event Loop
JavaScript Event LoopJavaScript Event Loop
JavaScript Event Loop
 
"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)
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
Nodejs - A quick tour (v6)
Nodejs - A quick tour (v6)Nodejs - A quick tour (v6)
Nodejs - A quick tour (v6)
 
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
 
Nodejs - Should Ruby Developers Care?
Nodejs - Should Ruby Developers Care?Nodejs - Should Ruby Developers Care?
Nodejs - Should Ruby Developers Care?
 
FITC - Node.js 101
FITC - Node.js 101FITC - Node.js 101
FITC - Node.js 101
 
Node azure
Node azureNode azure
Node azure
 
Building and Scaling Node.js Applications
Building and Scaling Node.js ApplicationsBuilding and Scaling Node.js Applications
Building and Scaling Node.js Applications
 
Nodejs a-practical-introduction-oredev
Nodejs a-practical-introduction-oredevNodejs a-practical-introduction-oredev
Nodejs a-practical-introduction-oredev
 
What I learned from FluentConf and then some
What I learned from FluentConf and then someWhat I learned from FluentConf and then some
What I learned from FluentConf and then some
 
Groovy & Grails eXchange 2012 vert.x presentation
Groovy & Grails eXchange 2012 vert.x presentationGroovy & Grails eXchange 2012 vert.x presentation
Groovy & Grails eXchange 2012 vert.x presentation
 
Node.js introduction
Node.js introductionNode.js introduction
Node.js introduction
 
Node.js 101 with Rami Sayar
Node.js 101 with Rami SayarNode.js 101 with Rami Sayar
Node.js 101 with Rami Sayar
 
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
 
Intro to node and mongodb 1
Intro to node and mongodb   1Intro to node and mongodb   1
Intro to node and mongodb 1
 
Practical Use of MongoDB for Node.js
Practical Use of MongoDB for Node.jsPractical Use of MongoDB for Node.js
Practical Use of MongoDB for Node.js
 
Intro To Node.js
Intro To Node.jsIntro To Node.js
Intro To Node.js
 
Node.js on Azure
Node.js on AzureNode.js on Azure
Node.js on Azure
 
GeekCampSG - Nodejs , Websockets and Realtime Web
GeekCampSG - Nodejs , Websockets and Realtime WebGeekCampSG - Nodejs , Websockets and Realtime Web
GeekCampSG - Nodejs , Websockets and Realtime Web
 

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
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
"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
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
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
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
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
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
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
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
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
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 

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)
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
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
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
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
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 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
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 

Introduction to Node.js: JavaScript Beyond the Browser

  • 1. Introduction to node.js End to end web development w/ javascript Or Kaplan kaplanor@gmail.com
  • 2. What is node? Taking JS Beyond the Browser Node.js is a framework for building scalable server-side applications and network oriented programs with asynchronous javascript.
  • 3. External modules Node modules (fs,tcp http) Node internals Google V8
  • 5. Before we start • JavaScript JavaScript JavaScript
  • 6. Hello world example setTimeout(function () { console.log("world"); }, 2000); console.log("hello"); setInterval(function () { console.log("world"); }, 2000); console.log("hello");
  • 7. The non-blocking notion • Single threaded • Instead of waiting use events • Never wait for IO (socket, disk etc.) • JS is natural for building async programs • For blocking operation the node internals uses thread pool to wait for operations to finish.
  • 8. Traditional I/O var data = file.read('file.txt'); process(data);
  • 9. Traditional I/O var data = file.read('file.txt'); ZzZzZZZzz… process(data); Why wasting those cycles?!
  • 10. Non-Blocking I/O file.read('file.txt', function (data) { process(data); return success; }); DoWhateverYouWishMeanwhile();
  • 11. Node Modules The true force of node
  • 12. NPM • NPM is a package manager for node.js – http://npmjs.org/
  • 13. Express Package • RESTful module for node webapps • Supports cookies, sessions, caching etc. • www.expressjs.com
  • 14. Example of Express API var Express = require('express'), app = Express.createServer(); app.get('/users/(:user)/?', function (req, res) { res.send('hello ' + req.params.user); }); app.listen(process.env.PORT || process.argv[3] || 8080);
  • 15. Comet Use Case • Comet is a way for the client to get a real time event from the server • How would you implement? – Polling – using AJAX to poll for events for events – Long Polling – Send HTTP requests in chain, the response is delayed. – Streaming – Keep open socket to the server.
  • 16. Requirements • Comet servers need to maintain many open connections • Holding one thread per connection is unacceptable • Node.js approach is better – easier to scale, less resources per connection.
  • 17. Implementing using web sockets • Introduced on HTML5 • Creating a thin layer over TCP/IP accepting constrain of the web • Supported by node.js • On this Demo we will use the socket.io module, which is HTML4 compatible web socket
  • 18. Chat Demo Chat server in less than 40 lines of code https://gist.github.com/4542595
  • 20. Exec – buffering (callback) var util = require('util'), exec = require('child_process').exec, child; child = exec('cat *.js bad_file | wc -l', function (error, stdout, stderr) { console.log('stdout: ' + stdout); console.log('stderr: ' + stderr); if (error !== null) { console.log('exec error: ' + error); } });
  • 21. Spawn - streaming var util = require('util'), spawn = require('child_process').spawn, ls = spawn('ls', ['-lh', '/usr']); ls.stdout.on('data', function (data) { console.log('stdout: ' + data); }); ls.stderr.on('data', function (data) { console.log('stderr: ' + data); }); ls.on('exit', function (code) { console.log('child process exited with code ' + code) ; });
  • 22. Live Site Tips • Test your code • Run static analysis • Monitor your app • Let it scale • Continuous deployment • Use process manager- SMF, forever or upstart • Document your code • Share code between client and server • Explore the community • Global uncaught exception handler • Chaos monkey
  • 23. Why should one use node.js • You already code your client using JS • Great Performance- http://four.livejournal.com/1019177.html • Can support thousands of concurrent connections • Easy to scale • Ideal for the mobile era • Fast development • Easy debug • No locks - V8 uses only one thread! • Community
  • 24. Good For • Small-Medium projects • Prototyping • Fast scale servers • Flexible dynamic application (inject code) • Web sockets
  • 25. Limitations • New programming style • Using only one thread • Immature environment • Limited stack trace • A bug may crash the whole server – use forever watch dog. • Dynamic language – what’s your religion?
  • 26. Some Patterns • Always return values on last statement • Pass callbacks • Code is not linear avoid infinite indentation (extract callback into named functions) • Promises • Test using node unit – high coverage is crucial
  • 27. Debugging (V8) • Builtin debugger- http://nodejs.org/docs/v0.5.9/api/debugger.html • Ndb - https://github.com/smtlaissezfaire/ndb • Inspector – web based (webkit) debugger - https://github.com/dannycoates/node-inspector • Web storm - http://www.jetbrains.com/webstorm/ • Eclipse - https://github.com/joyent/node/wiki/Using- Eclipse-as-Node-Applications-Debugger
  • 28. CoffeeScript • A ruby like scripting language that compiles to JavaScript. • Quick guide - http://jashkenas.github.com/coffee-script/ • Great slides at http://bodil.github.com/coffeescript/
  • 29. References • Node.js – http://www.nodejs.org • Comet - http://amix.dk/blog/post/19577 • Comet - http://www.slideshare.net/amix3k/comet-with-nodejs-and-v8 • WebSockets - http://howtonode.org/websockets-socketio • Best Practices - http://stella.laurenzo.org/2011/03/bulletproof-node-js- coding/ • Best Practices - http://howtonode.org • Node modules - https://github.com/joyent/node/wiki/modules • Node on Production - http://dshaw.github.com/2012-05-jsday/#/16
  • 30. Questions? Or Kaplan kaplanor@gmail.com

Notes de l'éditeur

  1. a. About meb. Agenda: 1. Short introduction to node 2. interpreter example 3. Express example (NPM + webstorm + Express + rest) 4. Socket.io chat example 5. some production tips
  2. Node "out of the box" isn't a web server like Apache; it's more of a language, like Ruby. You start with a blank slate, on top of which you can code a daemon, an IRC server, a process manager, or a blog - there's no automatic handling of virtualhosts, requests, responses, webroots, or any of the components that a LAMP stack (for example) assumes you want. The node community is building infrastructural components that can be dropped in, and I expect that the more I delve into the ecosystem, the more familiar I'll become with those components. At its core, however, Node is simply an API for asynchronous I/O methods.
  3. Nodejistu, joyent, heroku, azure
  4. Before we start I advice you to study JS since it has some small points and pitfalls that you should be fimiliar with, such as closures etc.The linked MDN tutorial is great to fill the gap.
  5. Arguably, Node.js’ most interesting feature is the performance of its evented, asynchronous, non-blocking IO. In javascript fashion, the vast majority of IO functions use callbacks to handle the ‘results’. This allows the logic of NodePing to branch out in several directions without IO processes blocking others. This handling works when talking to databases, reading and writing files, and talking to other machines via network protocols.Node uses the same technique as NGINX which uses only one thread to implement event driven server, making it high performance and scalable framework.Nginx is one of a handful of servers written to address the C10K problem. Unlike traditional servers, Nginx doesn't rely on threads to handle requests. Instead it uses a much more scalable event-driven (asynchronous) architecture. This architecture uses small, but more importantly, predictable amounts of memory under load.Even if you don't expect to handle thousands of simultaneous requests, you can still benefit from Nginx's high-performance and small memory footprint. Nginx scales in all directions: from the smallest VPS all the way up to clusters of servers.Nginx powers several high-visibility sites, such as WordPress, Hulu, Github, Ohloh, SourceForge, WhitePages and TorrentReactor.It’s almost impossible to get traditional I/O, which is good because of the design of the system.JS – its design is great for non-blocking I/O: - events on the browsers - anonymous functions and closures are part of the language.What’s different between node and any other platformInstead of waiting use eventsUse only one thread for processingNever wait for IO (socket, disk etc.)JS is natural for building async programsFor blocking operation the node internals uses thread pool to wait for operations to finish.
  6. All programs that emit events are instances of process.EventEmitterA promise is an EventEmitter which emits either success o
  7. Small core with crucial modules:HTTP/S, timers, url and paths, stdio, zlib, dns, file system, crypto
  8. Repository of modules, contains modules and its dependencies as it was compiledShow how I’m installing a package?For windows I use nji.exe but npm is an option as well.
  9. Types of comet:Long Polling – send new request every X seconds (e.g. FB)Streaming – leave open connection, on each event send response to the client but leave the channel open.
  10. Have a short Demo of socket.io chatShow web storm environment (my favorite IDE)How to debug
  11. Nevertheless, there are APIs which let you use buffering such as exec, which is a wrapper of spawn which get a callback
  12. By default node does not force you to buffer, this is example of creating new process and get the data on a stream.The architecture give emphasize on streaming and using of chunked responses, to avoid holding buffers in memory.
  13. By default node does not force you to buffer, this is example of creating new process and get the data on a stream.The architecture give emphasize on streaming and using of chunked responses, to avoid holding buffers in memory.process.on('uncaughtException', function (err) { console.error('Caught exception: ' + err) })This a dynamic world, read modules code and subscribe to mailing lists
  14. V8 has only single process and single thread. (the internal implementation is using thread pool for blocking operations)