SlideShare uma empresa Scribd logo
1 de 21
Baixar para ler offline
Introduction to Node.js:
 What, why and how?
    Christian Joudrey - @cjoudrey
“Node's goal is to provide an easy way to build
scalable network programs.”
What is node?

• Command line tool to run JavaScript:
  $ node my_app.js

• Built on top of Google's V8 JavaScript engine

• Provides a JavaScript API for network and file system

• Event-based, non-blocking I/O APIs
my_app.js:

  setTimeout(function () {
    console.log('world');
  }, 2000);

  console.log('hello');


Running it:
  $ node my_app.js
  hello
  world
The cost of I/O?

• Accessing RAM               ~ 250 CPU cycles

• Disk operations            ~ 41 000 000 CPU cycles
  o Reading a file
  o Writing to a file

• Network I/O                ~ 240 000 000 CPU cycles
  o Database query responses
  o Http responses
  o Memcache results
• I/O is expensive

• Most web applications are I/O bound, not CPU bound
Handling I/O

• Apache is multithreaded (depending on conf.)
   o Spawns a thread per request (or process)

• Each request is in its own "box", blocking I/O is "okay".



result = query('SELECT * FROM ...');
print result.id;
Thread-per-connection is expensive




http://blog.webfaction.com/a-little-holiday-present
• nginx uses an event-loop, like node.
Enter node...

• Single thread for your code

• ...but, I/O runs in parallel

• Handle thousands of concurrent connections with a single
  process

• Need to be very careful with CPU-intensive code
I/O in node

• No function should directly perform I/O.

• To receive info from disk, network, or another process there
  must be a callback.

• Callbacks are typically in the format:
  function (err, result) { }


query('SELECT * FROM ...', function (err, result){
  if (!err) {
    print result.id;
  }
});
CommonJS Module System

mymodule.js:

module.exports.add = function (a, b) {
   return a + b;
};


Using the module:

var mymodule = require('mymodule');
console.log(mymodule.add(5, 2));
Built-in Modules

• File System
 require('fs');

• HTTP Client and Server
 require('http');

• TCP Sockets
 require('net');

• Many more: http://nodejs.org/docs/v0.4.8/api/
Getting Started

• Node.js: http://nodejs.org/#download

• Build instructions: http://bit.ly/egLfzu
  Mac: brew update && brew install node
• npm, a package manager for Node:
  curl http://npmjs.org/install.sh | sh

• Many modules at: http://search.npmjs.org/

• Windows support isn't great (for the moment)
Reading a JSON File
 var fs = require('fs');
 var file = __dirname + '/test.json';

 fs.readFile(file, 'utf8', function (err, data) {
   if (err) {
     console.log('Error: ' + err);
     return;
   }

    data = JSON.parse(data);

   console.dir(data);
 });




https://gist.github.com/988107
Simple HTTP Server

 var http = require('http');

 var s = http.createServer(function (req, res) {
   var headers = {'Content-Type': 'text/html'};
   req.writeHead(200, headers);
   res.end('<h1>hello world</h1>');
 });

 s.listen(8080, '127.0.0.1');




https://gist.github.com/988108
Express makes HTTP easier

• Node's HTTP module is low level.

• Express is a simple framework inspired by Sinatra (Ruby).

• Installing Express:
  npm install express && npm install jade

• Robust verb-based routing
   o   app.get('/about', function(req, res) { });
   o   app.post('/login', function(req, res) { });

• Templating (with Jade or EJS)

• Sessions
Getting Started with Express

• Generate skeleton apps:
  express –help

• Generate app with sessions and template engine:
  express --sessions --template jade hello/

• Generated structure:
  $ ls hello/
  app.js logs     pids   public   test   views

  $ ls hello/views/
  index.jade layout.jade
Useful Modules

• Express - Sinatra-like Web Framework
  http://expressjs.com
  npm install express

• Jade - HAML-like Template Engine
  http://jade-lang.com
  npm install jade

• Socket.IO - Cross-browser WebSocket library
  http://socket.io/
  npm install socket.io
Interesting Links

• Lots of Express examples: http://bit.ly/ExpressExamples

• Express Documentation: http://bit.ly/ExpressDocs

• NodeMTL.com Source Code: http://bit.ly/iZCjod

• Database wrappers and ORMs:
  o   Mongoose (MongoDB, ORM-like):
      https://github.com/LearnBoost/mongoose
  o   Couch-ar (CouchDB, Active Record implementation):
      https://github.com/scottburch/couch-ar
Questions? :)

Mais conteúdo relacionado

Mais procurados

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
 
Node js presentation
Node js presentationNode js presentation
Node js presentation
martincabrera
 
OSCON 2011 - Node.js Tutorial
OSCON 2011 - Node.js TutorialOSCON 2011 - Node.js Tutorial
OSCON 2011 - Node.js Tutorial
Tom Croucher
 

Mais procurados (20)

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
Introduction to Node jsIntroduction to Node js
Introduction to Node js
 
Non-blocking I/O, Event loops and node.js
Non-blocking I/O, Event loops and node.jsNon-blocking I/O, Event loops and node.js
Non-blocking I/O, Event loops and node.js
 
Node ppt
Node pptNode ppt
Node ppt
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
Introduction to node.js aka NodeJS
Introduction to node.js aka NodeJSIntroduction to node.js aka NodeJS
Introduction to node.js aka NodeJS
 
Node js
Node jsNode js
Node js
 
NodeJS for Beginner
NodeJS for BeginnerNodeJS for Beginner
NodeJS for Beginner
 
Node js introduction
Node js introductionNode js introduction
Node js introduction
 
Node js presentation
Node js presentationNode js presentation
Node js presentation
 
Node.js - A Quick Tour
Node.js - A Quick TourNode.js - A Quick Tour
Node.js - A Quick Tour
 
All aboard the NodeJS Express
All aboard the NodeJS ExpressAll aboard the NodeJS Express
All aboard the NodeJS Express
 
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
 
JavaScript Event Loop
JavaScript Event LoopJavaScript Event Loop
JavaScript Event Loop
 
OSCON 2011 - Node.js Tutorial
OSCON 2011 - Node.js TutorialOSCON 2011 - Node.js Tutorial
OSCON 2011 - Node.js Tutorial
 
NodeJS Concurrency
NodeJS ConcurrencyNodeJS Concurrency
NodeJS Concurrency
 
Server Side Event Driven Programming
Server Side Event Driven ProgrammingServer Side Event Driven Programming
Server Side Event Driven Programming
 
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
 
Node.js, for architects - OpenSlava 2013
Node.js, for architects - OpenSlava 2013Node.js, for architects - OpenSlava 2013
Node.js, for architects - OpenSlava 2013
 
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
 

Semelhante a Introduction to Node.js: What, why and how?

Node.js introduction
Node.js introductionNode.js introduction
Node.js introduction
Prasoon Kumar
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
Richard Lee
 
nodejs_at_a_glance.ppt
nodejs_at_a_glance.pptnodejs_at_a_glance.ppt
nodejs_at_a_glance.ppt
WalaSidhom1
 
Intro to node and mongodb 1
Intro to node and mongodb   1Intro to node and mongodb   1
Intro to node and mongodb 1
Mohammad Qureshi
 

Semelhante a Introduction to Node.js: What, why and how? (20)

GeekCampSG - Nodejs , Websockets and Realtime Web
GeekCampSG - Nodejs , Websockets and Realtime WebGeekCampSG - Nodejs , Websockets and Realtime Web
GeekCampSG - Nodejs , Websockets and Realtime Web
 
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
 
Node.js introduction
Node.js introductionNode.js introduction
Node.js introduction
 
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
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
FITC - Node.js 101
FITC - Node.js 101FITC - Node.js 101
FITC - Node.js 101
 
Node.js: The What, The How and The When
Node.js: The What, The How and The WhenNode.js: The What, The How and The When
Node.js: The What, The How and The When
 
Tech io nodejs_20130531_v0.6
Tech io nodejs_20130531_v0.6Tech io nodejs_20130531_v0.6
Tech io nodejs_20130531_v0.6
 
Introduction to Node (15th May 2017)
Introduction to Node (15th May 2017)Introduction to Node (15th May 2017)
Introduction to Node (15th May 2017)
 
Node.js
Node.jsNode.js
Node.js
 
Introduction to NodeJS with LOLCats
Introduction to NodeJS with LOLCatsIntroduction to NodeJS with LOLCats
Introduction to NodeJS with LOLCats
 
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
 
"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)
 
nodejs_at_a_glance.ppt
nodejs_at_a_glance.pptnodejs_at_a_glance.ppt
nodejs_at_a_glance.ppt
 
Node.js 101 with Rami Sayar
Node.js 101 with Rami SayarNode.js 101 with Rami Sayar
Node.js 101 with Rami Sayar
 
Nodejs a-practical-introduction-oredev
Nodejs a-practical-introduction-oredevNodejs a-practical-introduction-oredev
Nodejs a-practical-introduction-oredev
 
Introducing Node.js in an Oracle technology environment (including hands-on)
Introducing Node.js in an Oracle technology environment (including hands-on)Introducing Node.js in an Oracle technology environment (including hands-on)
Introducing Node.js in an Oracle technology environment (including hands-on)
 
Intro to node and mongodb 1
Intro to node and mongodb   1Intro to node and mongodb   1
Intro to node and mongodb 1
 
Node.js - The New, New Hotness
Node.js - The New, New HotnessNode.js - The New, New Hotness
Node.js - The New, New Hotness
 
Node.js Workshop - Sela SDP 2015
Node.js Workshop  - Sela SDP 2015Node.js Workshop  - Sela SDP 2015
Node.js Workshop - Sela SDP 2015
 

Último

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 

Último (20)

Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
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...
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source Milvus
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
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
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 

Introduction to Node.js: What, why and how?

  • 1. Introduction to Node.js: What, why and how? Christian Joudrey - @cjoudrey
  • 2. “Node's goal is to provide an easy way to build scalable network programs.”
  • 3. What is node? • Command line tool to run JavaScript: $ node my_app.js • Built on top of Google's V8 JavaScript engine • Provides a JavaScript API for network and file system • Event-based, non-blocking I/O APIs
  • 4. my_app.js: setTimeout(function () { console.log('world'); }, 2000); console.log('hello'); Running it: $ node my_app.js hello world
  • 5. The cost of I/O? • Accessing RAM ~ 250 CPU cycles • Disk operations ~ 41 000 000 CPU cycles o Reading a file o Writing to a file • Network I/O ~ 240 000 000 CPU cycles o Database query responses o Http responses o Memcache results
  • 6. • I/O is expensive • Most web applications are I/O bound, not CPU bound
  • 7. Handling I/O • Apache is multithreaded (depending on conf.) o Spawns a thread per request (or process) • Each request is in its own "box", blocking I/O is "okay". result = query('SELECT * FROM ...'); print result.id;
  • 9. • nginx uses an event-loop, like node.
  • 10. Enter node... • Single thread for your code • ...but, I/O runs in parallel • Handle thousands of concurrent connections with a single process • Need to be very careful with CPU-intensive code
  • 11. I/O in node • No function should directly perform I/O. • To receive info from disk, network, or another process there must be a callback. • Callbacks are typically in the format: function (err, result) { } query('SELECT * FROM ...', function (err, result){ if (!err) { print result.id; } });
  • 12. CommonJS Module System mymodule.js: module.exports.add = function (a, b) { return a + b; }; Using the module: var mymodule = require('mymodule'); console.log(mymodule.add(5, 2));
  • 13. Built-in Modules • File System require('fs'); • HTTP Client and Server require('http'); • TCP Sockets require('net'); • Many more: http://nodejs.org/docs/v0.4.8/api/
  • 14. Getting Started • Node.js: http://nodejs.org/#download • Build instructions: http://bit.ly/egLfzu Mac: brew update && brew install node • npm, a package manager for Node: curl http://npmjs.org/install.sh | sh • Many modules at: http://search.npmjs.org/ • Windows support isn't great (for the moment)
  • 15. Reading a JSON File var fs = require('fs'); var file = __dirname + '/test.json'; fs.readFile(file, 'utf8', function (err, data) { if (err) { console.log('Error: ' + err); return; } data = JSON.parse(data); console.dir(data); }); https://gist.github.com/988107
  • 16. Simple HTTP Server var http = require('http'); var s = http.createServer(function (req, res) { var headers = {'Content-Type': 'text/html'}; req.writeHead(200, headers); res.end('<h1>hello world</h1>'); }); s.listen(8080, '127.0.0.1'); https://gist.github.com/988108
  • 17. Express makes HTTP easier • Node's HTTP module is low level. • Express is a simple framework inspired by Sinatra (Ruby). • Installing Express: npm install express && npm install jade • Robust verb-based routing o app.get('/about', function(req, res) { }); o app.post('/login', function(req, res) { }); • Templating (with Jade or EJS) • Sessions
  • 18. Getting Started with Express • Generate skeleton apps: express –help • Generate app with sessions and template engine: express --sessions --template jade hello/ • Generated structure: $ ls hello/ app.js logs pids public test views $ ls hello/views/ index.jade layout.jade
  • 19. Useful Modules • Express - Sinatra-like Web Framework http://expressjs.com npm install express • Jade - HAML-like Template Engine http://jade-lang.com npm install jade • Socket.IO - Cross-browser WebSocket library http://socket.io/ npm install socket.io
  • 20. Interesting Links • Lots of Express examples: http://bit.ly/ExpressExamples • Express Documentation: http://bit.ly/ExpressDocs • NodeMTL.com Source Code: http://bit.ly/iZCjod • Database wrappers and ORMs: o Mongoose (MongoDB, ORM-like): https://github.com/LearnBoost/mongoose o Couch-ar (CouchDB, Active Record implementation): https://github.com/scottburch/couch-ar