SlideShare a Scribd company logo
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? :)

More Related Content

What's hot (20)

PDF
Node.js and How JavaScript is Changing Server Programming
Tom Croucher
 
PPTX
Introduction to Node js
Akshay Mathur
 
PDF
Non-blocking I/O, Event loops and node.js
Marcus Frödin
 
PDF
Node ppt
Tamil Selvan R S
 
PPTX
Introduction to Node.js
Vikash Singh
 
PPT
Introduction to node.js aka NodeJS
JITENDRA KUMAR PATEL
 
PDF
Node js
Rohan Chandane
 
PDF
NodeJS for Beginner
Apaichon Punopas
 
PPTX
Node js introduction
Joseph de Castelnau
 
PPT
Node js presentation
martincabrera
 
PDF
Node.js - A Quick Tour
Felix Geisendörfer
 
PDF
All aboard the NodeJS Express
David Boyer
 
KEY
node.js: Javascript's in your backend
David Padbury
 
PPT
JavaScript Event Loop
Thomas Hunter II
 
KEY
OSCON 2011 - Node.js Tutorial
Tom Croucher
 
PPTX
NodeJS Concurrency
pgriess
 
PDF
Server Side Event Driven Programming
Kamal Hussain
 
PPTX
Intro to node and non blocking io
Amy Hua
 
PPTX
Node.js, for architects - OpenSlava 2013
Oscar Renalias
 
PPT
RESTful API In Node Js using Express
Jeetendra singh
 
Node.js and How JavaScript is Changing Server Programming
Tom Croucher
 
Introduction to Node js
Akshay Mathur
 
Non-blocking I/O, Event loops and node.js
Marcus Frödin
 
Introduction to Node.js
Vikash Singh
 
Introduction to node.js aka NodeJS
JITENDRA KUMAR PATEL
 
NodeJS for Beginner
Apaichon Punopas
 
Node js introduction
Joseph de Castelnau
 
Node js presentation
martincabrera
 
Node.js - A Quick Tour
Felix Geisendörfer
 
All aboard the NodeJS Express
David Boyer
 
node.js: Javascript's in your backend
David Padbury
 
JavaScript Event Loop
Thomas Hunter II
 
OSCON 2011 - Node.js Tutorial
Tom Croucher
 
NodeJS Concurrency
pgriess
 
Server Side Event Driven Programming
Kamal Hussain
 
Intro to node and non blocking io
Amy Hua
 
Node.js, for architects - OpenSlava 2013
Oscar Renalias
 
RESTful API In Node Js using Express
Jeetendra singh
 

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

PPTX
GeekCampSG - Nodejs , Websockets and Realtime Web
Bhagaban Behera
 
PDF
Basic Understanding and Implement of Node.js
Gary Yeh
 
PDF
Node.js introduction
Prasoon Kumar
 
KEY
Practical Use of MongoDB for Node.js
async_io
 
PDF
Introduction to Node.js
Richard Lee
 
PDF
FITC - Node.js 101
Rami Sayar
 
PPTX
Node.js: The What, The How and The When
FITC
 
PDF
Tech io nodejs_20130531_v0.6
Ganesh Kondal
 
PPTX
Introduction to Node (15th May 2017)
Lucas Jellema
 
KEY
Node.js
Ian Oxley
 
KEY
Introduction to NodeJS with LOLCats
Derek Anderson
 
PPT
nodejs_at_a_glance, understanding java script
mohammedarshadhussai4
 
PDF
Introduction to node js - From "hello world" to deploying on azure
Colin Mackay
 
PDF
"You Don't Know NODE.JS" by Hengki Mardongan Sihombing (Urbanhire)
Tech in Asia ID
 
PPT
nodejs_at_a_glance.ppt
WalaSidhom1
 
PDF
Node.js 101 with Rami Sayar
FITC
 
PDF
Nodejs a-practical-introduction-oredev
Felix Geisendörfer
 
PPTX
Introducing Node.js in an Oracle technology environment (including hands-on)
Lucas Jellema
 
PPTX
Intro to node and mongodb 1
Mohammad Qureshi
 
KEY
Node.js - The New, New Hotness
Daniel Shaw
 
GeekCampSG - Nodejs , Websockets and Realtime Web
Bhagaban Behera
 
Basic Understanding and Implement of Node.js
Gary Yeh
 
Node.js introduction
Prasoon Kumar
 
Practical Use of MongoDB for Node.js
async_io
 
Introduction to Node.js
Richard Lee
 
FITC - Node.js 101
Rami Sayar
 
Node.js: The What, The How and The When
FITC
 
Tech io nodejs_20130531_v0.6
Ganesh Kondal
 
Introduction to Node (15th May 2017)
Lucas Jellema
 
Node.js
Ian Oxley
 
Introduction to NodeJS with LOLCats
Derek Anderson
 
nodejs_at_a_glance, understanding java script
mohammedarshadhussai4
 
Introduction to node js - From "hello world" to deploying on azure
Colin Mackay
 
"You Don't Know NODE.JS" by Hengki Mardongan Sihombing (Urbanhire)
Tech in Asia ID
 
nodejs_at_a_glance.ppt
WalaSidhom1
 
Node.js 101 with Rami Sayar
FITC
 
Nodejs a-practical-introduction-oredev
Felix Geisendörfer
 
Introducing Node.js in an Oracle technology environment (including hands-on)
Lucas Jellema
 
Intro to node and mongodb 1
Mohammad Qureshi
 
Node.js - The New, New Hotness
Daniel Shaw
 
Ad

Recently uploaded (20)

PDF
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
PDF
Transcript: Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
PDF
“Voice Interfaces on a Budget: Building Real-time Speech Recognition on Low-c...
Edge AI and Vision Alliance
 
PPTX
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
PDF
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
PPTX
Future Tech Innovations 2025 – A TechLists Insight
TechLists
 
PPTX
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
PDF
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
PDF
“Squinting Vision Pipelines: Detecting and Correcting Errors in Vision Models...
Edge AI and Vision Alliance
 
PPTX
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
PDF
How do you fast track Agentic automation use cases discovery?
DianaGray10
 
PDF
NLJUG Speaker academy 2025 - first session
Bert Jan Schrijver
 
PDF
NASA A Researcher’s Guide to International Space Station : Physical Sciences ...
Dr. PANKAJ DHUSSA
 
PDF
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
PDF
SIZING YOUR AIR CONDITIONER---A PRACTICAL GUIDE.pdf
Muhammad Rizwan Akram
 
PDF
Future-Proof or Fall Behind? 10 Tech Trends You Can’t Afford to Ignore in 2025
DIGITALCONFEX
 
PDF
LOOPS in C Programming Language - Technology
RishabhDwivedi43
 
PDF
UPDF - AI PDF Editor & Converter Key Features
DealFuel
 
PDF
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
PDF
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
Transcript: Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
“Voice Interfaces on a Budget: Building Real-time Speech Recognition on Low-c...
Edge AI and Vision Alliance
 
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
Future Tech Innovations 2025 – A TechLists Insight
TechLists
 
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
“Squinting Vision Pipelines: Detecting and Correcting Errors in Vision Models...
Edge AI and Vision Alliance
 
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
How do you fast track Agentic automation use cases discovery?
DianaGray10
 
NLJUG Speaker academy 2025 - first session
Bert Jan Schrijver
 
NASA A Researcher’s Guide to International Space Station : Physical Sciences ...
Dr. PANKAJ DHUSSA
 
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
SIZING YOUR AIR CONDITIONER---A PRACTICAL GUIDE.pdf
Muhammad Rizwan Akram
 
Future-Proof or Fall Behind? 10 Tech Trends You Can’t Afford to Ignore in 2025
DIGITALCONFEX
 
LOOPS in C Programming Language - Technology
RishabhDwivedi43
 
UPDF - AI PDF Editor & Converter Key Features
DealFuel
 
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 
Ad

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