SlideShare uma empresa Scribd logo
1 de 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

Mais conteúdo relacionado

Mais procurados

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
 

Mais procurados (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
 

Destaque

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
 

Destaque (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
 

Semelhante a 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
 

Semelhante a 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
 

Último

GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
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
 
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
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
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
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
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
 
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
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
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
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
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
 

Último (20)

GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
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
 
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...
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
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
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
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
 
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
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
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...
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
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
 

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

Notas do Editor

  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)