SlideShare ist ein Scribd-Unternehmen logo
1 von 31
Intro to Node.js
        Chris Cowan
            Lead Engineer
    http://www.plus3network.com
Node’s Goal is to provide an
 easy way to build scalable
    network programs.
Node.js is NOT another
  web framework!

  But you can create a web framework using NPM modules.
Node.js is…
             Web Server
              TCP Server
     Awesome Robot Controller
     Command Line Application
            Proxy Server
          Streaming Server
          VoiceMail Server
           Music Machine
Anything that has to deal with high I/O
Node.js is
Server Side JavaScript!
Node.js is

FUN!
Why Node.js?
• Non Blocking I/O
• Based on Chrome’s V8 Engines (FAST!)
• 15,000+ Modules
• Active Community (IRC, Mailing
  Lists, Twitter, Github)
• Mac, Linux and Windows (all first class citizens)
• One Language for Frontend and Backend
• JavaScript is the Language of the Web
Installing Node.js
Mac OS X
1. Go to http://nodejs.org and click install
2. Install the downloaded package

Windows
1. Go to http://nodejs.org and click install
2. Install the downloaded package

Linux (and *nix variants)
1. Go to http://nodejs.org and click install
2. Decompress source and… ./configure … make … make install
   ( for Ubuntu use Chris Lea’s PPA – ppa:chris-lea/node.js )
Some Basic
 Examples
Hello World
Create hello-world.js
console.log(‘Hello World’);

On the command line run
node hello-world.js

You should see
Hello World
Basic HTTP Server
var http = require('http');

var server = http.createServer(function (req, res) {
  res.writeHead(200);
  res.end('Hello World');
});

server.listen(4000);



                   *Running this script my development box,
                   I can achieve 10,000+ requests per second
                        with 100 concurrent connections
                            without breaking a sweat
Some people use the
 core http module to
build their web apps,
most use a framework
     like Express
 or Connect or Flatiron or Tako or Derby or Geddy or Mojito or …
Visit
http://expressjs.com/guide.html
       for a detailed guide
         on using Express
What is Non-Blocking I/O?
    And why should I care?
Blocking I/
// Get User – 20ms
$query = 'SELECT * FROM users WHERE id = ?';
$users = query($query, array($id));
print_r($users);

// Get Activities – 100ms
$query = 'SELECT * FROM activities ORDER BY timestamp LIMIT 50';
$activities = query($query);
print_r($activities);

// Get Leader Board – 150ms
$query = 'SELECT count(points) as total, user_id FROM activities LIMIT 50';
$leader_board = query($query);




          270ms = SUM(user, activities, leaderboard)
Non-Blocking I/
// Get User – 20ms
var query = 'SELECT * FROM users WHERE id = ?';
db.query(query, [userId], function (err, results) {
  console.log(results);
});

// Get Activities – 100ms
var query = 'SELECT * FROM activities ORDER BY timestamp LIMIT 50';
db.query(query, function (err, results) {
  console.log(results);
});

// Get Leader Board – 150ms
var query = 'SELECT count(points) as total, user_id FROM activities LIMIT 50';
db.query(query, function (err, results) {
  console.log(results);
});




           150ms = MAX(user, activities, leaderboard)
The most jarring thing
about Server Side JavaScript
  is thinking in callbacks
The Node Callback Pattern
awesomeFunction(arg, function (err, data) {
   if (err) {
      // Handle Error
   }
   // Do something awesome with results.
});

• Error first then success… ALWAYS!
• Because this is the de-facto standard 99.99999% of the time
  you will be able to guess how a Node library will work.
Callbacks are the Devil’s Work!
                          Don’t go down this rabbit hole…
var userQuery = 'SELECT * FROM users WHERE id = ?';
var activityQuery = 'SELECT * FROM activities ORDER BY timestamp LIMIT 50';
var leaderBoardQuery = 'SELECT count(points) as total, user_id FROM activities LIMIT 50';

db.query(userQuery, [id], function (userErr, userResults) {
 db.query(activityQuery, function (activityErr, activityResults) {
    db.query(leaderBoardQuery, function (leaderBoardErr, leaderBoardResults) {

        // Do something here

      });
   });
});


   One of the biggest mistakes is to get yourself in
    to callback hell by nesting callbacks inside of
          callbacks inside of more callbacks.
Avoiding Callback Hell
• Keep your code shallow
• Break up your code into small chunks
• Use a sequential library like async
• Visit http://callbackhell.com
Async to the rescue!
var async = require('async');
var db = require(’db');

function getUser (callback) {
  var query = 'SELECT * FROM users WHERE id = ?';
  db.query(query, [userId], callback);
}

function getActivities (callback) {
  var query = 'SELECT * FROM activities ORDER BY timestamp LIMIT 50';
  db.query(query, callback);
}

function getLeaderBoard (callback) {
  var query = 'SELECT count(points) as total, user_id FROM activities LIMIT 50';
  db.query(query, callback);
}

var tasks = [getUser, getActivities, getLeaderBoard];
async.parallel(tasks, function (err, results) {
  var user       = results[0][0];
  var activities = results[1];
  var leaderBoard = results[2];
});
Async provides several useful
 patterns for asynchronous control
            flow including:
 parallel, series, waterfall, auto and
                queue.
                      Visit
        https://github.com/caolan/async
for a detailed guide on using the async module.
The Node Package Manager
 otherwise know as… NPM

 It’s how you harness the
    awesomeness of the
    Node.js community!
Using NPM
It’s standard practice to install modules locally for your current project.
Modules are installed in the ./node_modules in the current directory.

To Install a new module

npm install <module>

To find a module in the NPM repository

npm search <search string>

To list the modules (and their dependencies) in the current project

npm list

To see module details

npm info <module>
DON’T INSTALL
MODULES GLOBALLY!
 Unless they are tools like node-dev, jake, express, minify-js
  OR linked development modules but more on that later.
NPM is awesome sauce!

               Visit
        https://npmjs.org
for more details about NPM and to
browse the current NPM Repository
Creating your own modules
• Node.js uses CommonJS Modules
• require(‘./example’) will load either
  example.js or example/index.js or the entry
  point specified in package.json
• Run npm init to bootstrap your new module
• Try to stick to creating Pure JavaScript
  modules if possible. It will give you less
  headaches down the road.
Basic Module Example
Everything exposed via module.exports is available as an instance variable.

var currentCount = 0;

module.exports.incr = function () {
  return ++currentCount;
};

Once you’ve created a module in counter.js you use it like this…
var counter = require(’./counter');
var count = counter.incr();

Keep this in mind… modules are loaded once and cached. So when
you load the module a second time in your app, require just
returns the cache copied. This lets you do interesting things…
Installing your module
• Run npm link in the module working directory
• Then run npm link <module> in the your project
  folder to link it from the global module to your
  local node_modules.

• OR you can create a private registry
  (See https://npmjs.org/doc/registry.html)

• OR just link it by hand :P
My Favorite Modules
• request      • jake
• async        • hogan.js
• node-dev     • connect
• underscore   • moment
• express      • mysql
Questions?
Contact me at chris@chriscowan.us

Weitere ähnliche Inhalte

Was ist angesagt?

Introduction to Node js
Introduction to Node jsIntroduction to Node js
Introduction to Node jsAkshay Mathur
 
All aboard the NodeJS Express
All aboard the NodeJS ExpressAll aboard the NodeJS Express
All aboard the NodeJS ExpressDavid Boyer
 
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
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applicationsTom Croucher
 
Java script at backend nodejs
Java script at backend   nodejsJava script at backend   nodejs
Java script at backend nodejsAmit Thakkar
 
OSCON 2011 - Node.js Tutorial
OSCON 2011 - Node.js TutorialOSCON 2011 - Node.js Tutorial
OSCON 2011 - Node.js TutorialTom Croucher
 
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
 
Node js presentation
Node js presentationNode js presentation
Node js presentationmartincabrera
 
Use Node.js to create a REST API
Use Node.js to create a REST APIUse Node.js to create a REST API
Use Node.js to create a REST APIFabien Vauchelles
 
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
 
NodeJS - Server Side JS
NodeJS - Server Side JS NodeJS - Server Side JS
NodeJS - Server Side JS Ganesh Kondal
 
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
 
Building servers with Node.js
Building servers with Node.jsBuilding servers with Node.js
Building servers with Node.jsConFoo
 
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
 
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.js Explained
Node.js ExplainedNode.js Explained
Node.js ExplainedJeff Kunkle
 

Was ist angesagt? (20)

Introduction to Node js
Introduction to Node jsIntroduction to Node js
Introduction to Node js
 
All aboard the NodeJS Express
All aboard the NodeJS ExpressAll aboard the NodeJS Express
All aboard the NodeJS Express
 
Nodejs intro
Nodejs introNodejs intro
Nodejs intro
 
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
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applications
 
Java script at backend nodejs
Java script at backend   nodejsJava script at backend   nodejs
Java script at backend nodejs
 
OSCON 2011 - Node.js Tutorial
OSCON 2011 - Node.js TutorialOSCON 2011 - Node.js Tutorial
OSCON 2011 - Node.js Tutorial
 
Node ppt
Node pptNode ppt
Node ppt
 
Node js introduction
Node js introductionNode js introduction
Node js introduction
 
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
 
Node js presentation
Node js presentationNode js presentation
Node js presentation
 
Use Node.js to create a REST API
Use Node.js to create a REST APIUse Node.js to create a REST API
Use Node.js to create a REST API
 
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
 
NodeJS - Server Side JS
NodeJS - Server Side JS NodeJS - Server Side JS
NodeJS - Server Side JS
 
Nodejs in Production
Nodejs in ProductionNodejs in Production
Nodejs in Production
 
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
 
Building servers with Node.js
Building servers with Node.jsBuilding servers with Node.js
Building servers with 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
 
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
 
Node.js Explained
Node.js ExplainedNode.js Explained
Node.js Explained
 

Andere mochten auch

Node.js In The Enterprise - A Primer
Node.js In The Enterprise - A PrimerNode.js In The Enterprise - A Primer
Node.js In The Enterprise - A PrimerNaveen S.R
 
Node.js in action
Node.js in actionNode.js in action
Node.js in actionSimon Su
 
#7 "Многообещающий JavaScript – Promises" Денис Речкунов
#7 "Многообещающий JavaScript – Promises" Денис Речкунов#7 "Многообещающий JavaScript – Promises" Денис Речкунов
#7 "Многообещающий JavaScript – Promises" Денис РечкуновJSib
 
Why Node, Express and Postgres - presented 23 Feb 15, Talkjs, Microsoft Audit...
Why Node, Express and Postgres - presented 23 Feb 15, Talkjs, Microsoft Audit...Why Node, Express and Postgres - presented 23 Feb 15, Talkjs, Microsoft Audit...
Why Node, Express and Postgres - presented 23 Feb 15, Talkjs, Microsoft Audit...Calvin Tan
 
Migrating a Monolithic App to Microservices on Cloud Foundry
Migrating a Monolithic App to Microservices on Cloud FoundryMigrating a Monolithic App to Microservices on Cloud Foundry
Migrating a Monolithic App to Microservices on Cloud FoundryTony Erwin
 
Microservices and modern backends - Azure Meetup Frankfurt
Microservices and modern backends  - Azure Meetup FrankfurtMicroservices and modern backends  - Azure Meetup Frankfurt
Microservices and modern backends - Azure Meetup FrankfurtDamir Dobric
 
A High-Performance Solution To Microservices UI Composition
A High-Performance Solution To Microservices UI CompositionA High-Performance Solution To Microservices UI Composition
A High-Performance Solution To Microservices UI CompositionAlexey Gravanov
 
Building a Web Frontend with Microservices and NGINX Plus
Building a Web Frontend with Microservices and NGINX PlusBuilding a Web Frontend with Microservices and NGINX Plus
Building a Web Frontend with Microservices and NGINX PlusNGINX, Inc.
 
Node.js & Twitter Bootstrap Crash Course
Node.js & Twitter Bootstrap Crash CourseNode.js & Twitter Bootstrap Crash Course
Node.js & Twitter Bootstrap Crash CourseAaron Silverman
 
Building microservices web application using scala & akka
Building microservices web application using scala & akkaBuilding microservices web application using scala & akka
Building microservices web application using scala & akkaBinh Nguyen
 
Burgas Conf 21.06.2014 - Single page application Angularjs and Nodejs
Burgas Conf 21.06.2014 - Single page application Angularjs and NodejsBurgas Conf 21.06.2014 - Single page application Angularjs and Nodejs
Burgas Conf 21.06.2014 - Single page application Angularjs and NodejsDimitar Danailov
 
Introduction to Node.js: perspectives from a Drupal dev
Introduction to Node.js: perspectives from a Drupal devIntroduction to Node.js: perspectives from a Drupal dev
Introduction to Node.js: perspectives from a Drupal devmcantelon
 
Webconf nodejs-production-architecture
Webconf nodejs-production-architectureWebconf nodejs-production-architecture
Webconf nodejs-production-architectureBen Lin
 
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
 
Building Scalable Web Applications Using Microservices Architecture and NodeJ...
Building Scalable Web Applications Using Microservices Architecture and NodeJ...Building Scalable Web Applications Using Microservices Architecture and NodeJ...
Building Scalable Web Applications Using Microservices Architecture and NodeJ...NodejsFoundation
 
An Unexpected Solution to Microservices UI Composition
An Unexpected Solution to Microservices UI CompositionAn Unexpected Solution to Microservices UI Composition
An Unexpected Solution to Microservices UI CompositionDr. Arif Wider
 
Complete MVC on NodeJS
Complete MVC on NodeJSComplete MVC on NodeJS
Complete MVC on NodeJSHüseyin BABAL
 
Nodejs Event Driven Concurrency for Web Applications
Nodejs Event Driven Concurrency for Web ApplicationsNodejs Event Driven Concurrency for Web Applications
Nodejs Event Driven Concurrency for Web ApplicationsGanesh Iyer
 
Create Rest API in Nodejs
Create Rest API in Nodejs Create Rest API in Nodejs
Create Rest API in Nodejs Irfan Maulana
 
Workshop 4: NodeJS. Express Framework & MongoDB.
Workshop 4: NodeJS. Express Framework & MongoDB.Workshop 4: NodeJS. Express Framework & MongoDB.
Workshop 4: NodeJS. Express Framework & MongoDB.Visual Engineering
 

Andere mochten auch (20)

Node.js In The Enterprise - A Primer
Node.js In The Enterprise - A PrimerNode.js In The Enterprise - A Primer
Node.js In The Enterprise - A Primer
 
Node.js in action
Node.js in actionNode.js in action
Node.js in action
 
#7 "Многообещающий JavaScript – Promises" Денис Речкунов
#7 "Многообещающий JavaScript – Promises" Денис Речкунов#7 "Многообещающий JavaScript – Promises" Денис Речкунов
#7 "Многообещающий JavaScript – Promises" Денис Речкунов
 
Why Node, Express and Postgres - presented 23 Feb 15, Talkjs, Microsoft Audit...
Why Node, Express and Postgres - presented 23 Feb 15, Talkjs, Microsoft Audit...Why Node, Express and Postgres - presented 23 Feb 15, Talkjs, Microsoft Audit...
Why Node, Express and Postgres - presented 23 Feb 15, Talkjs, Microsoft Audit...
 
Migrating a Monolithic App to Microservices on Cloud Foundry
Migrating a Monolithic App to Microservices on Cloud FoundryMigrating a Monolithic App to Microservices on Cloud Foundry
Migrating a Monolithic App to Microservices on Cloud Foundry
 
Microservices and modern backends - Azure Meetup Frankfurt
Microservices and modern backends  - Azure Meetup FrankfurtMicroservices and modern backends  - Azure Meetup Frankfurt
Microservices and modern backends - Azure Meetup Frankfurt
 
A High-Performance Solution To Microservices UI Composition
A High-Performance Solution To Microservices UI CompositionA High-Performance Solution To Microservices UI Composition
A High-Performance Solution To Microservices UI Composition
 
Building a Web Frontend with Microservices and NGINX Plus
Building a Web Frontend with Microservices and NGINX PlusBuilding a Web Frontend with Microservices and NGINX Plus
Building a Web Frontend with Microservices and NGINX Plus
 
Node.js & Twitter Bootstrap Crash Course
Node.js & Twitter Bootstrap Crash CourseNode.js & Twitter Bootstrap Crash Course
Node.js & Twitter Bootstrap Crash Course
 
Building microservices web application using scala & akka
Building microservices web application using scala & akkaBuilding microservices web application using scala & akka
Building microservices web application using scala & akka
 
Burgas Conf 21.06.2014 - Single page application Angularjs and Nodejs
Burgas Conf 21.06.2014 - Single page application Angularjs and NodejsBurgas Conf 21.06.2014 - Single page application Angularjs and Nodejs
Burgas Conf 21.06.2014 - Single page application Angularjs and Nodejs
 
Introduction to Node.js: perspectives from a Drupal dev
Introduction to Node.js: perspectives from a Drupal devIntroduction to Node.js: perspectives from a Drupal dev
Introduction to Node.js: perspectives from a Drupal dev
 
Webconf nodejs-production-architecture
Webconf nodejs-production-architectureWebconf nodejs-production-architecture
Webconf nodejs-production-architecture
 
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
 
Building Scalable Web Applications Using Microservices Architecture and NodeJ...
Building Scalable Web Applications Using Microservices Architecture and NodeJ...Building Scalable Web Applications Using Microservices Architecture and NodeJ...
Building Scalable Web Applications Using Microservices Architecture and NodeJ...
 
An Unexpected Solution to Microservices UI Composition
An Unexpected Solution to Microservices UI CompositionAn Unexpected Solution to Microservices UI Composition
An Unexpected Solution to Microservices UI Composition
 
Complete MVC on NodeJS
Complete MVC on NodeJSComplete MVC on NodeJS
Complete MVC on NodeJS
 
Nodejs Event Driven Concurrency for Web Applications
Nodejs Event Driven Concurrency for Web ApplicationsNodejs Event Driven Concurrency for Web Applications
Nodejs Event Driven Concurrency for Web Applications
 
Create Rest API in Nodejs
Create Rest API in Nodejs Create Rest API in Nodejs
Create Rest API in Nodejs
 
Workshop 4: NodeJS. Express Framework & MongoDB.
Workshop 4: NodeJS. Express Framework & MongoDB.Workshop 4: NodeJS. Express Framework & MongoDB.
Workshop 4: NodeJS. Express Framework & MongoDB.
 

Ähnlich wie Node.js Intro - Server Side JavaScript, Non-Blocking I/O, and Awesome Modules

Intro to node and mongodb 1
Intro to node and mongodb   1Intro to node and mongodb   1
Intro to node and mongodb 1Mohammad Qureshi
 
Intro to Node.js (v1)
Intro to Node.js (v1)Intro to Node.js (v1)
Intro to Node.js (v1)Chris Cowan
 
A complete guide to Node.js
A complete guide to Node.jsA complete guide to Node.js
A complete guide to Node.jsPrabin Silwal
 
JavaScript Modules Done Right
JavaScript Modules Done RightJavaScript Modules Done Right
JavaScript Modules Done RightMariusz Nowak
 
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
 
Introducing the Seneca MVP framework for Node.js
Introducing the Seneca MVP framework for Node.jsIntroducing the Seneca MVP framework for Node.js
Introducing the Seneca MVP framework for Node.jsRichard Rodger
 
Introduction to node.js GDD
Introduction to node.js GDDIntroduction to node.js GDD
Introduction to node.js GDDSudar Muthu
 
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
 
Introduction to REST API with Node.js
Introduction to REST API with Node.jsIntroduction to REST API with Node.js
Introduction to REST API with Node.jsYoann Gotthilf
 
Node js introduction
Node js introductionNode js introduction
Node js introductionAlex Su
 
JS & NodeJS - An Introduction
JS & NodeJS - An IntroductionJS & NodeJS - An Introduction
JS & NodeJS - An IntroductionNirvanic Labs
 
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
 
Tech io nodejs_20130531_v0.6
Tech io nodejs_20130531_v0.6Tech io nodejs_20130531_v0.6
Tech io nodejs_20130531_v0.6Ganesh Kondal
 
Introduce about Nodejs - duyetdev.com
Introduce about Nodejs - duyetdev.comIntroduce about Nodejs - duyetdev.com
Introduce about Nodejs - duyetdev.comVan-Duyet Le
 
Introduction to NodeJS with LOLCats
Introduction to NodeJS with LOLCatsIntroduction to NodeJS with LOLCats
Introduction to NodeJS with LOLCatsDerek Anderson
 
Reactive application using meteor
Reactive application using meteorReactive application using meteor
Reactive application using meteorSapna Upreti
 

Ähnlich wie Node.js Intro - Server Side JavaScript, Non-Blocking I/O, and Awesome Modules (20)

Intro to node and mongodb 1
Intro to node and mongodb   1Intro to node and mongodb   1
Intro to node and mongodb 1
 
Intro to Node.js (v1)
Intro to Node.js (v1)Intro to Node.js (v1)
Intro to Node.js (v1)
 
A complete guide to Node.js
A complete guide to Node.jsA complete guide to Node.js
A complete guide to Node.js
 
Node.js essentials
 Node.js essentials Node.js essentials
Node.js essentials
 
Node azure
Node azureNode azure
Node azure
 
JavaScript Modules Done Right
JavaScript Modules Done RightJavaScript Modules Done Right
JavaScript Modules Done Right
 
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
 
Introducing the Seneca MVP framework for Node.js
Introducing the Seneca MVP framework for Node.jsIntroducing the Seneca MVP framework for Node.js
Introducing the Seneca MVP framework for Node.js
 
20120816 nodejsdublin
20120816 nodejsdublin20120816 nodejsdublin
20120816 nodejsdublin
 
Introduction to node.js GDD
Introduction to node.js GDDIntroduction to node.js GDD
Introduction to node.js GDD
 
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
 
Introduction to REST API with Node.js
Introduction to REST API with Node.jsIntroduction to REST API with Node.js
Introduction to REST API with Node.js
 
Node js introduction
Node js introductionNode js introduction
Node js introduction
 
JS & NodeJS - An Introduction
JS & NodeJS - An IntroductionJS & NodeJS - An Introduction
JS & NodeJS - An Introduction
 
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
 
Tech io nodejs_20130531_v0.6
Tech io nodejs_20130531_v0.6Tech io nodejs_20130531_v0.6
Tech io nodejs_20130531_v0.6
 
Introduce about Nodejs - duyetdev.com
Introduce about Nodejs - duyetdev.comIntroduce about Nodejs - duyetdev.com
Introduce about Nodejs - duyetdev.com
 
Introduction to NodeJS with LOLCats
Introduction to NodeJS with LOLCatsIntroduction to NodeJS with LOLCats
Introduction to NodeJS with LOLCats
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
Reactive application using meteor
Reactive application using meteorReactive application using meteor
Reactive application using meteor
 

Kürzlich hochgeladen

Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
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
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
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
 
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
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
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
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
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
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
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
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
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
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 

Kürzlich hochgeladen (20)

Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
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
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
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
 
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
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
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
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
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
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
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
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
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
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 

Node.js Intro - Server Side JavaScript, Non-Blocking I/O, and Awesome Modules

  • 1. Intro to Node.js Chris Cowan Lead Engineer http://www.plus3network.com
  • 2. Node’s Goal is to provide an easy way to build scalable network programs.
  • 3. Node.js is NOT another web framework! But you can create a web framework using NPM modules.
  • 4. Node.js is… Web Server TCP Server Awesome Robot Controller Command Line Application Proxy Server Streaming Server VoiceMail Server Music Machine Anything that has to deal with high I/O
  • 7. Why Node.js? • Non Blocking I/O • Based on Chrome’s V8 Engines (FAST!) • 15,000+ Modules • Active Community (IRC, Mailing Lists, Twitter, Github) • Mac, Linux and Windows (all first class citizens) • One Language for Frontend and Backend • JavaScript is the Language of the Web
  • 8. Installing Node.js Mac OS X 1. Go to http://nodejs.org and click install 2. Install the downloaded package Windows 1. Go to http://nodejs.org and click install 2. Install the downloaded package Linux (and *nix variants) 1. Go to http://nodejs.org and click install 2. Decompress source and… ./configure … make … make install ( for Ubuntu use Chris Lea’s PPA – ppa:chris-lea/node.js )
  • 10. Hello World Create hello-world.js console.log(‘Hello World’); On the command line run node hello-world.js You should see Hello World
  • 11. Basic HTTP Server var http = require('http'); var server = http.createServer(function (req, res) { res.writeHead(200); res.end('Hello World'); }); server.listen(4000); *Running this script my development box, I can achieve 10,000+ requests per second with 100 concurrent connections without breaking a sweat
  • 12. Some people use the core http module to build their web apps, most use a framework like Express or Connect or Flatiron or Tako or Derby or Geddy or Mojito or …
  • 13. Visit http://expressjs.com/guide.html for a detailed guide on using Express
  • 14. What is Non-Blocking I/O? And why should I care?
  • 15. Blocking I/ // Get User – 20ms $query = 'SELECT * FROM users WHERE id = ?'; $users = query($query, array($id)); print_r($users); // Get Activities – 100ms $query = 'SELECT * FROM activities ORDER BY timestamp LIMIT 50'; $activities = query($query); print_r($activities); // Get Leader Board – 150ms $query = 'SELECT count(points) as total, user_id FROM activities LIMIT 50'; $leader_board = query($query); 270ms = SUM(user, activities, leaderboard)
  • 16. Non-Blocking I/ // Get User – 20ms var query = 'SELECT * FROM users WHERE id = ?'; db.query(query, [userId], function (err, results) { console.log(results); }); // Get Activities – 100ms var query = 'SELECT * FROM activities ORDER BY timestamp LIMIT 50'; db.query(query, function (err, results) { console.log(results); }); // Get Leader Board – 150ms var query = 'SELECT count(points) as total, user_id FROM activities LIMIT 50'; db.query(query, function (err, results) { console.log(results); }); 150ms = MAX(user, activities, leaderboard)
  • 17. The most jarring thing about Server Side JavaScript is thinking in callbacks
  • 18. The Node Callback Pattern awesomeFunction(arg, function (err, data) { if (err) { // Handle Error } // Do something awesome with results. }); • Error first then success… ALWAYS! • Because this is the de-facto standard 99.99999% of the time you will be able to guess how a Node library will work.
  • 19. Callbacks are the Devil’s Work! Don’t go down this rabbit hole… var userQuery = 'SELECT * FROM users WHERE id = ?'; var activityQuery = 'SELECT * FROM activities ORDER BY timestamp LIMIT 50'; var leaderBoardQuery = 'SELECT count(points) as total, user_id FROM activities LIMIT 50'; db.query(userQuery, [id], function (userErr, userResults) { db.query(activityQuery, function (activityErr, activityResults) { db.query(leaderBoardQuery, function (leaderBoardErr, leaderBoardResults) { // Do something here }); }); }); One of the biggest mistakes is to get yourself in to callback hell by nesting callbacks inside of callbacks inside of more callbacks.
  • 20. Avoiding Callback Hell • Keep your code shallow • Break up your code into small chunks • Use a sequential library like async • Visit http://callbackhell.com
  • 21. Async to the rescue! var async = require('async'); var db = require(’db'); function getUser (callback) { var query = 'SELECT * FROM users WHERE id = ?'; db.query(query, [userId], callback); } function getActivities (callback) { var query = 'SELECT * FROM activities ORDER BY timestamp LIMIT 50'; db.query(query, callback); } function getLeaderBoard (callback) { var query = 'SELECT count(points) as total, user_id FROM activities LIMIT 50'; db.query(query, callback); } var tasks = [getUser, getActivities, getLeaderBoard]; async.parallel(tasks, function (err, results) { var user = results[0][0]; var activities = results[1]; var leaderBoard = results[2]; });
  • 22. Async provides several useful patterns for asynchronous control flow including: parallel, series, waterfall, auto and queue. Visit https://github.com/caolan/async for a detailed guide on using the async module.
  • 23. The Node Package Manager otherwise know as… NPM It’s how you harness the awesomeness of the Node.js community!
  • 24. Using NPM It’s standard practice to install modules locally for your current project. Modules are installed in the ./node_modules in the current directory. To Install a new module npm install <module> To find a module in the NPM repository npm search <search string> To list the modules (and their dependencies) in the current project npm list To see module details npm info <module>
  • 25. DON’T INSTALL MODULES GLOBALLY! Unless they are tools like node-dev, jake, express, minify-js OR linked development modules but more on that later.
  • 26. NPM is awesome sauce! Visit https://npmjs.org for more details about NPM and to browse the current NPM Repository
  • 27. Creating your own modules • Node.js uses CommonJS Modules • require(‘./example’) will load either example.js or example/index.js or the entry point specified in package.json • Run npm init to bootstrap your new module • Try to stick to creating Pure JavaScript modules if possible. It will give you less headaches down the road.
  • 28. Basic Module Example Everything exposed via module.exports is available as an instance variable. var currentCount = 0; module.exports.incr = function () { return ++currentCount; }; Once you’ve created a module in counter.js you use it like this… var counter = require(’./counter'); var count = counter.incr(); Keep this in mind… modules are loaded once and cached. So when you load the module a second time in your app, require just returns the cache copied. This lets you do interesting things…
  • 29. Installing your module • Run npm link in the module working directory • Then run npm link <module> in the your project folder to link it from the global module to your local node_modules. • OR you can create a private registry (See https://npmjs.org/doc/registry.html) • OR just link it by hand :P
  • 30. My Favorite Modules • request • jake • async • hogan.js • node-dev • connect • underscore • moment • express • mysql
  • 31. Questions? Contact me at chris@chriscowan.us