SlideShare une entreprise Scribd logo
1  sur  21
Télécharger pour lire hors ligne
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? :)

Contenu connexe

Tendances

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
Introduction to Node jsIntroduction to Node js
Introduction to Node jsAkshay Mathur
 
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
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.jsVikash Singh
 
Introduction to node.js aka NodeJS
Introduction to node.js aka NodeJSIntroduction to node.js aka NodeJS
Introduction to node.js aka NodeJSJITENDRA KUMAR PATEL
 
Node js presentation
Node js presentationNode js presentation
Node js presentationmartincabrera
 
All aboard the NodeJS Express
All aboard the NodeJS ExpressAll aboard the NodeJS Express
All aboard the NodeJS ExpressDavid Boyer
 
node.js: Javascript's in your backend
node.js: Javascript's in your backendnode.js: Javascript's in your backend
node.js: Javascript's in your backendDavid Padbury
 
OSCON 2011 - Node.js Tutorial
OSCON 2011 - Node.js TutorialOSCON 2011 - Node.js Tutorial
OSCON 2011 - Node.js TutorialTom Croucher
 
NodeJS Concurrency
NodeJS ConcurrencyNodeJS Concurrency
NodeJS Concurrencypgriess
 
Server Side Event Driven Programming
Server Side Event Driven ProgrammingServer Side Event Driven Programming
Server Side Event Driven ProgrammingKamal Hussain
 
Intro to node and non blocking io
Intro to node and non blocking ioIntro to node and non blocking io
Intro to node and non blocking ioAmy Hua
 
Node.js, for architects - OpenSlava 2013
Node.js, for architects - OpenSlava 2013Node.js, for architects - OpenSlava 2013
Node.js, for architects - OpenSlava 2013Oscar Renalias
 
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
 

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

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

GeekCampSG - Nodejs , Websockets and Realtime Web
GeekCampSG - Nodejs , Websockets and Realtime WebGeekCampSG - Nodejs , Websockets and Realtime Web
GeekCampSG - Nodejs , Websockets and Realtime WebBhagaban Behera
 
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
 
Node.js introduction
Node.js introductionNode.js introduction
Node.js introductionPrasoon Kumar
 
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
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.jsRichard Lee
 
FITC - Node.js 101
FITC - Node.js 101FITC - Node.js 101
FITC - Node.js 101Rami Sayar
 
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 WhenFITC
 
Tech io nodejs_20130531_v0.6
Tech io nodejs_20130531_v0.6Tech io nodejs_20130531_v0.6
Tech io nodejs_20130531_v0.6Ganesh Kondal
 
Introduction to Node (15th May 2017)
Introduction to Node (15th May 2017)Introduction to Node (15th May 2017)
Introduction to Node (15th May 2017)Lucas Jellema
 
Introduction to NodeJS with LOLCats
Introduction to NodeJS with LOLCatsIntroduction to NodeJS with LOLCats
Introduction to NodeJS with LOLCatsDerek Anderson
 
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
 
"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
 
nodejs_at_a_glance.ppt
nodejs_at_a_glance.pptnodejs_at_a_glance.ppt
nodejs_at_a_glance.pptWalaSidhom1
 
Node.js 101 with Rami Sayar
Node.js 101 with Rami SayarNode.js 101 with Rami Sayar
Node.js 101 with Rami SayarFITC
 
Nodejs a-practical-introduction-oredev
Nodejs a-practical-introduction-oredevNodejs a-practical-introduction-oredev
Nodejs a-practical-introduction-oredevFelix Geisendörfer
 
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)Lucas Jellema
 
Intro to node and mongodb 1
Intro to node and mongodb   1Intro to node and mongodb   1
Intro to node and mongodb 1Mohammad Qureshi
 
Node.js - The New, New Hotness
Node.js - The New, New HotnessNode.js - The New, New Hotness
Node.js - The New, New HotnessDaniel Shaw
 
Node.js Workshop - Sela SDP 2015
Node.js Workshop  - Sela SDP 2015Node.js Workshop  - Sela SDP 2015
Node.js Workshop - Sela SDP 2015Nir Noy
 

Similaire à 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
 

Dernier

Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
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
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
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
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
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
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
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
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilV3cube
 
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
 
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
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
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
 
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
 

Dernier (20)

Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
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
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
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
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
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
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
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...
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
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
 
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...
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
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
 
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
 

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