SlideShare uma empresa Scribd logo
1 de 37
Building a real-life
application in Node JS
       Darren Waddell
ME ME ME ME ME

     • MooTools Developer
     • Love JavaScript!
     • C# Developer
     • Love building big apps!
OMG
JAVASCRIPT
SERVER!
‘Real-life applications’

• Websites
• Content Management Systems
• Blog Engines
• (Not games, chat programs, ‘Native HTML5’
  fish demos)
I’LL BUILD
A CMS!
What did I need to
      start

   • OSX! (or linux)
   • Install Node and NPM
   • A DB (MongoDB)
Confusing things!

• Non-blocking, event driven, asynchronous
• NoSQL
• Modules and NPM
• No Firebug!
Things I need for my
          app

• Routing
• Database
• Templating
Express
                  Setting up server




var app = require('express').createServer();

app.get('/', function(req, res){
  res.send('hello world');
});

app.listen(80);
Express
              Setting up View handler



app.set('view engine', 'jade');
app.set('views', __dirname + '/views');

app.get('/foo/bar', function(req, res){
  res.render('foo/bar');
  // calls /views/foo/bar.jade
});

app.listen(80);
Express
              Setting up ‘static assets’

var app = require('express').createServer();

app.use(
    express.static(__dirname + '/public')
);

<script type=”foo.js”></script>
// is at http://foo.com/foo.js
// NOT http://foo.com/public/foo.js
Express
             Passing data to views



app.get('/foo/bar', function(req, res){
  res.render('foo/bar', {
    locals: {
      foo: ‘bar’
    }
  });
});
Express
             Passing data to views




app.get('/users/:id', function(req, res){
    // req.params contains
    // the querystring values
    var id = req.params.id;
});
Express
              Passing data to views



app.use(express.bodyParser());

app.post('/users/:id', function(req, res){
    // req.body contains the postback
    var username = req.body.name;
});
Express
                ‘Master Pages’




app.set('view options', {
    layout: 'shared/layout'
});

app.get('/foo/bar', function(req, res){
    res.render('foo/bar');
});
Things I need for my
          app

• Routing
• Database
• Templating
Mongo DB
• No tables! ‘Collections’
• No Rows! ‘Documents’
• No columns! ‘Fields’
• JSON format!
• No SQL joins!
• Flexible table collection structure
Mongo DB


select * from ‘foo’

 db.foo.find({});
Mongo DB
insert into ‘foo’
set (‘foobar’)
values (‘whatever’);


db.foo.insert({
   ‘foobar’: ‘whatever’
});
Mongo DB

delete from ‘foo’
where ‘name’ = ‘Darren’



db.foo.remove({
    ‘name’:‘Darren’
});
Mongoose

• Models
• Getters and Setters, Defaults,Validators
• Avoid callback soup (very important!)
Mongoose
                           Simple modelling

var mongoose = require(‘mongoose’);
mongoose.connect(‘mongodb://localhost/myDB’);

var User = new mongoose.Schema({

 username: String,

 fullname: String,
   password: String
});

var myUserModel = mongoose.model(‘User’);

myUserModel.find({}, function(err, docs){
   docs.forEach(function(user){
      // do stuff
   });
});
Mongoose
                           Simple modelling


var mongoose = require(‘mongoose’);
mongoose.connect(‘mongodb://localhost/myDB’);

var User = new mongoose.Schema({

 username: String,

 fullname: String,

 password: String
});

var myUserModel = mongoose.model(‘User’);

myUserModel.username = ‘fakedarren’;
myUserModel.fullname = ‘William Waddell’;

myUserModel.save();
Mongoose
                  Simple modelling




var myUserModel = mongoose.model(‘User’);

myUserModel.username = ‘fakedarren’;
myUserModel.fullname = ‘William Waddell’;

myUserModel.save();
MongooseDefault values




var mongoose = require(‘mongoose’);
mongoose.connect(‘mongodb://localhost/myDB’);

var User = new mongoose.Schema({

 username: String,

 fullname: String,

 password: String,

 role: {

 
 type: String,

 
 default: ‘Admin’

 }
});
Mongoose
                          Getters and Setters


var mongoose = require(‘mongoose’);
mongoose.connect(‘mongodb://localhost/myDB’);

var User = new mongoose.Schema({

 username: String,

 fullname: String,

 password: String
});

User.path(‘password’).set(function(value){

 if (password.length < 8){

 
 return new Error(‘Password must be more than 8 characters’);

 } else {

 
 return value;

 }
});
Mongoose
                  Middleware / promises / whatever it’s called


User.pre(‘save’, function(next){

 // do something

 next();
});
User.pre(‘save’, function(next){

 // do something else

 next();
});

var myUserModel = mongoose.model(‘User’);

myUserModel.username = ‘fakedarren’;
myUserModel.fullname = ‘William Waddell’;

myUserModel.save();
Things I need for my
          app

• Routing
• Database
• Templating
View Engines

       HAML
         Jade
          EJS
      CoffeeKup
   jQuery Templates
View Engines

       HAML
         Jade
          EJS
      CoffeeKup
   jQuery Templates
Jade
http://jade-lang.com/


!!! 5
html(lang="en")
  head
    title= pageTitle
    script(type='text/javascript')
       if (foo) {
          bar()
       }
  body
    h1 Jade - node template engine
    #container
       - if (youAreUsingJade)
         p You are amazing
       - else
         p Get on it!
!!! 5
html(lang="en")
  head
    title= pageTitle
    script(type='text/javascript')
       if (foo) {
          bar()
       }
  body
    h1 Jade - node template engine
    #container
       - if (youAreUsingJade)
         p You are amazing
       - else
         p Get on it!
EJS
https://github.com/visionmedia/ejs


       <!DOCTYPE html>
       <html>
       <head>
       <title>Awesome</title>
       </head>
       <body>
       <% if (names.length) { %>
       <ul>
           <% names.forEach(function(name){ %>
             <li><%= name %></li>
           <% }) %>
         </ul>
       <% } %>
       </body>
       </html>
<!DOCTYPE html>
<html>
<head>
<title>Awesome</title>
</head>
<body>
<% if (names.length) { %>
<ul>
    <% names.forEach(function(name){ %>
      <li><%= name %></li>
    <% }) %>
  </ul>
<% } %>
</body>
</html>
Things I need for my
          app

• Routing
• Database
• Templating
Things I need for my
           app
• Routing
• Database
• Templating
• And a million other things....
Thanks!
            @fakedarren

https://github.com/fakedarren/node-cms

Mais conteúdo relacionado

Mais procurados

Java script at backend nodejs
Java script at backend   nodejsJava script at backend   nodejs
Java script at backend nodejsAmit Thakkar
 
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
 
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
 
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
 
Nodejs Explained with Examples
Nodejs Explained with ExamplesNodejs Explained with Examples
Nodejs Explained with ExamplesGabriele Lana
 
Node.js Patterns for Discerning Developers
Node.js Patterns for Discerning DevelopersNode.js Patterns for Discerning Developers
Node.js Patterns for Discerning Developerscacois
 
Node.js and How JavaScript is Changing Server Programming
Node.js and How JavaScript is Changing Server Programming  Node.js and How JavaScript is Changing Server Programming
Node.js and How JavaScript is Changing Server Programming Tom Croucher
 
Introduction to node.js GDD
Introduction to node.js GDDIntroduction to node.js GDD
Introduction to node.js GDDSudar Muthu
 
Introduction to node.js
Introduction to node.jsIntroduction to node.js
Introduction to node.jsjacekbecela
 
Intro to Node.js (v1)
Intro to Node.js (v1)Intro to Node.js (v1)
Intro to Node.js (v1)Chris Cowan
 
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
 
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
 
A language for the Internet: Why JavaScript and Node.js is right for Internet...
A language for the Internet: Why JavaScript and Node.js is right for Internet...A language for the Internet: Why JavaScript and Node.js is right for Internet...
A language for the Internet: Why JavaScript and Node.js is right for Internet...Tom Croucher
 

Mais procurados (20)

Java script at backend nodejs
Java script at backend   nodejsJava script at backend   nodejs
Java script at backend nodejs
 
Express node js
Express node jsExpress node js
Express node js
 
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
 
Express js
Express jsExpress js
Express 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 js presentation
Node js presentationNode js presentation
Node js presentation
 
All aboard the NodeJS Express
All aboard the NodeJS ExpressAll aboard the NodeJS Express
All aboard the NodeJS Express
 
Nodejs Explained with Examples
Nodejs Explained with ExamplesNodejs Explained with Examples
Nodejs Explained with Examples
 
Node.js Patterns for Discerning Developers
Node.js Patterns for Discerning DevelopersNode.js Patterns for Discerning Developers
Node.js Patterns for Discerning Developers
 
Node.js - Best practices
Node.js  - Best practicesNode.js  - Best practices
Node.js - Best practices
 
Node.js
Node.jsNode.js
Node.js
 
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 GDD
Introduction to node.js GDDIntroduction to node.js GDD
Introduction to node.js GDD
 
Introduction to node.js
Introduction to node.jsIntroduction to node.js
Introduction to node.js
 
Intro to Node.js (v1)
Intro to Node.js (v1)Intro to Node.js (v1)
Intro to Node.js (v1)
 
Node ppt
Node pptNode ppt
Node ppt
 
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
 
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
 
A language for the Internet: Why JavaScript and Node.js is right for Internet...
A language for the Internet: Why JavaScript and Node.js is right for Internet...A language for the Internet: Why JavaScript and Node.js is right for Internet...
A language for the Internet: Why JavaScript and Node.js is right for Internet...
 
NodeJS for Beginner
NodeJS for BeginnerNodeJS for Beginner
NodeJS for Beginner
 

Destaque

Getting Started with MongoDB and Node.js
Getting Started with MongoDB and Node.jsGetting Started with MongoDB and Node.js
Getting Started with MongoDB and Node.jsGrant Goodale
 
It is not supposed to fly but it does
It is not supposed to fly but it doesIt is not supposed to fly but it does
It is not supposed to fly but it doesGabriele Lana
 
Anatomy of a Modern Node.js Application Architecture
Anatomy of a Modern Node.js Application Architecture Anatomy of a Modern Node.js Application Architecture
Anatomy of a Modern Node.js Application Architecture AppDynamics
 
Node Foundation Membership Overview 20160907
Node Foundation Membership Overview 20160907Node Foundation Membership Overview 20160907
Node Foundation Membership Overview 20160907NodejsFoundation
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.jsVikash Singh
 
S2 b desenvolvimento de sistemas [reparado]
S2 b   desenvolvimento de sistemas [reparado]S2 b   desenvolvimento de sistemas [reparado]
S2 b desenvolvimento de sistemas [reparado]Milena Rebouças
 
Node.js - un poco de informacion.
Node.js - un poco de informacion.Node.js - un poco de informacion.
Node.js - un poco de informacion.Luis Toscano
 
Running Node.js in Production using Passenger
Running Node.js in Production using PassengerRunning Node.js in Production using Passenger
Running Node.js in Production using Passengerdavidchubbs
 
Node in Production at Aviary
Node in Production at AviaryNode in Production at Aviary
Node in Production at AviaryAviary
 
Node JS (Francisco Cerdas)
Node JS (Francisco Cerdas)Node JS (Francisco Cerdas)
Node JS (Francisco Cerdas)PiXeL16
 
Membangun Website Lowongan Kerja Sederhana dengan NodeJS
Membangun Website Lowongan Kerja Sederhana dengan NodeJSMembangun Website Lowongan Kerja Sederhana dengan NodeJS
Membangun Website Lowongan Kerja Sederhana dengan NodeJSRidwan Fadjar
 
Webinar: Developing with the modern App Stack: MEAN and MERN (with Angular2 a...
Webinar: Developing with the modern App Stack: MEAN and MERN (with Angular2 a...Webinar: Developing with the modern App Stack: MEAN and MERN (with Angular2 a...
Webinar: Developing with the modern App Stack: MEAN and MERN (with Angular2 a...MongoDB
 
Nodifying the Enterprise - Prince Soni, TO THE NEW
Nodifying the Enterprise - Prince Soni, TO THE NEWNodifying the Enterprise - Prince Soni, TO THE NEW
Nodifying the Enterprise - Prince Soni, TO THE NEWNodejsFoundation
 
Connecting NodeJS & MongoDB
Connecting NodeJS & MongoDBConnecting NodeJS & MongoDB
Connecting NodeJS & MongoDBEnoch Joshua
 
Node JS Express : Steps to Create Restful Web App
Node JS Express : Steps to Create Restful Web AppNode JS Express : Steps to Create Restful Web App
Node JS Express : Steps to Create Restful Web AppEdureka!
 

Destaque (20)

Getting Started with MongoDB and Node.js
Getting Started with MongoDB and Node.jsGetting Started with MongoDB and Node.js
Getting Started with MongoDB and Node.js
 
Node.js and Ruby
Node.js and RubyNode.js and Ruby
Node.js and Ruby
 
It is not supposed to fly but it does
It is not supposed to fly but it doesIt is not supposed to fly but it does
It is not supposed to fly but it does
 
Anatomy of a Modern Node.js Application Architecture
Anatomy of a Modern Node.js Application Architecture Anatomy of a Modern Node.js Application Architecture
Anatomy of a Modern Node.js Application Architecture
 
Node Foundation Membership Overview 20160907
Node Foundation Membership Overview 20160907Node Foundation Membership Overview 20160907
Node Foundation Membership Overview 20160907
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
S2 b desenvolvimento de sistemas [reparado]
S2 b   desenvolvimento de sistemas [reparado]S2 b   desenvolvimento de sistemas [reparado]
S2 b desenvolvimento de sistemas [reparado]
 
Node.js - un poco de informacion.
Node.js - un poco de informacion.Node.js - un poco de informacion.
Node.js - un poco de informacion.
 
Node.js - A Quick Tour II
Node.js - A Quick Tour IINode.js - A Quick Tour II
Node.js - A Quick Tour II
 
Running Node.js in Production using Passenger
Running Node.js in Production using PassengerRunning Node.js in Production using Passenger
Running Node.js in Production using Passenger
 
Node in Production at Aviary
Node in Production at AviaryNode in Production at Aviary
Node in Production at Aviary
 
Node JS (Francisco Cerdas)
Node JS (Francisco Cerdas)Node JS (Francisco Cerdas)
Node JS (Francisco Cerdas)
 
Membangun Website Lowongan Kerja Sederhana dengan NodeJS
Membangun Website Lowongan Kerja Sederhana dengan NodeJSMembangun Website Lowongan Kerja Sederhana dengan NodeJS
Membangun Website Lowongan Kerja Sederhana dengan NodeJS
 
Introducción a Node.js
Introducción a Node.jsIntroducción a Node.js
Introducción a Node.js
 
Beyond Phoenix
Beyond PhoenixBeyond Phoenix
Beyond Phoenix
 
Webinar: Developing with the modern App Stack: MEAN and MERN (with Angular2 a...
Webinar: Developing with the modern App Stack: MEAN and MERN (with Angular2 a...Webinar: Developing with the modern App Stack: MEAN and MERN (with Angular2 a...
Webinar: Developing with the modern App Stack: MEAN and MERN (with Angular2 a...
 
Nodifying the Enterprise - Prince Soni, TO THE NEW
Nodifying the Enterprise - Prince Soni, TO THE NEWNodifying the Enterprise - Prince Soni, TO THE NEW
Nodifying the Enterprise - Prince Soni, TO THE NEW
 
Connecting NodeJS & MongoDB
Connecting NodeJS & MongoDBConnecting NodeJS & MongoDB
Connecting NodeJS & MongoDB
 
Node JS Express : Steps to Create Restful Web App
Node JS Express : Steps to Create Restful Web AppNode JS Express : Steps to Create Restful Web App
Node JS Express : Steps to Create Restful Web App
 
Mongo DB
Mongo DB Mongo DB
Mongo DB
 

Semelhante a Building a real life application in node js

Javascript MVC & Backbone Tips & Tricks
Javascript MVC & Backbone Tips & TricksJavascript MVC & Backbone Tips & Tricks
Javascript MVC & Backbone Tips & TricksHjörtur Hilmarsson
 
Introduction to node.js
Introduction to node.jsIntroduction to node.js
Introduction to node.jsAdrien Guéret
 
The go-start webframework (GTUG Vienna 27.03.2012)
The go-start webframework (GTUG Vienna 27.03.2012)The go-start webframework (GTUG Vienna 27.03.2012)
The go-start webframework (GTUG Vienna 27.03.2012)ungerik
 
Build web application by express
Build web application by expressBuild web application by express
Build web application by expressShawn Meng
 
Mojolicious, real-time web framework
Mojolicious, real-time web frameworkMojolicious, real-time web framework
Mojolicious, real-time web frameworktaggg
 
WordPress as the Backbone(.js)
WordPress as the Backbone(.js)WordPress as the Backbone(.js)
WordPress as the Backbone(.js)Beau Lebens
 
Beyond DOMReady: Ultra High-Performance Javascript
Beyond DOMReady: Ultra High-Performance JavascriptBeyond DOMReady: Ultra High-Performance Javascript
Beyond DOMReady: Ultra High-Performance Javascriptaglemann
 
Javascript first-class citizenery
Javascript first-class citizeneryJavascript first-class citizenery
Javascript first-class citizenerytoddbr
 
SproutCore and the Future of Web Apps
SproutCore and the Future of Web AppsSproutCore and the Future of Web Apps
SproutCore and the Future of Web AppsMike Subelsky
 
Styling components with JavaScript
Styling components with JavaScriptStyling components with JavaScript
Styling components with JavaScriptbensmithett
 
[Coscup 2012] JavascriptMVC
[Coscup 2012] JavascriptMVC[Coscup 2012] JavascriptMVC
[Coscup 2012] JavascriptMVCAlive Kuo
 
Week 4 - jQuery + Ajax
Week 4 - jQuery + AjaxWeek 4 - jQuery + Ajax
Week 4 - jQuery + Ajaxbaygross
 
Dependency Management with RequireJS
Dependency Management with RequireJSDependency Management with RequireJS
Dependency Management with RequireJSAaronius
 
FrontInBahia 2014: 10 dicas de desempenho para apps mobile híbridas
FrontInBahia 2014: 10 dicas de desempenho para apps mobile híbridasFrontInBahia 2014: 10 dicas de desempenho para apps mobile híbridas
FrontInBahia 2014: 10 dicas de desempenho para apps mobile híbridasLoiane Groner
 
MIKE Stack Introduction - MongoDB, io.js, KendoUI, and Express
MIKE Stack Introduction - MongoDB, io.js, KendoUI, and ExpressMIKE Stack Introduction - MongoDB, io.js, KendoUI, and Express
MIKE Stack Introduction - MongoDB, io.js, KendoUI, and ExpressCharlie Key
 
WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...Fabio Franzini
 
#NewMeetup Performance
#NewMeetup Performance#NewMeetup Performance
#NewMeetup PerformanceJustin Cataldo
 
Practical HTML5: Using It Today
Practical HTML5: Using It TodayPractical HTML5: Using It Today
Practical HTML5: Using It TodayDoris Chen
 
An Introduction to Tornado
An Introduction to TornadoAn Introduction to Tornado
An Introduction to TornadoGavin Roy
 
PHP and Rich Internet Applications
PHP and Rich Internet ApplicationsPHP and Rich Internet Applications
PHP and Rich Internet Applicationselliando dias
 

Semelhante a Building a real life application in node js (20)

Javascript MVC & Backbone Tips & Tricks
Javascript MVC & Backbone Tips & TricksJavascript MVC & Backbone Tips & Tricks
Javascript MVC & Backbone Tips & Tricks
 
Introduction to node.js
Introduction to node.jsIntroduction to node.js
Introduction to node.js
 
The go-start webframework (GTUG Vienna 27.03.2012)
The go-start webframework (GTUG Vienna 27.03.2012)The go-start webframework (GTUG Vienna 27.03.2012)
The go-start webframework (GTUG Vienna 27.03.2012)
 
Build web application by express
Build web application by expressBuild web application by express
Build web application by express
 
Mojolicious, real-time web framework
Mojolicious, real-time web frameworkMojolicious, real-time web framework
Mojolicious, real-time web framework
 
WordPress as the Backbone(.js)
WordPress as the Backbone(.js)WordPress as the Backbone(.js)
WordPress as the Backbone(.js)
 
Beyond DOMReady: Ultra High-Performance Javascript
Beyond DOMReady: Ultra High-Performance JavascriptBeyond DOMReady: Ultra High-Performance Javascript
Beyond DOMReady: Ultra High-Performance Javascript
 
Javascript first-class citizenery
Javascript first-class citizeneryJavascript first-class citizenery
Javascript first-class citizenery
 
SproutCore and the Future of Web Apps
SproutCore and the Future of Web AppsSproutCore and the Future of Web Apps
SproutCore and the Future of Web Apps
 
Styling components with JavaScript
Styling components with JavaScriptStyling components with JavaScript
Styling components with JavaScript
 
[Coscup 2012] JavascriptMVC
[Coscup 2012] JavascriptMVC[Coscup 2012] JavascriptMVC
[Coscup 2012] JavascriptMVC
 
Week 4 - jQuery + Ajax
Week 4 - jQuery + AjaxWeek 4 - jQuery + Ajax
Week 4 - jQuery + Ajax
 
Dependency Management with RequireJS
Dependency Management with RequireJSDependency Management with RequireJS
Dependency Management with RequireJS
 
FrontInBahia 2014: 10 dicas de desempenho para apps mobile híbridas
FrontInBahia 2014: 10 dicas de desempenho para apps mobile híbridasFrontInBahia 2014: 10 dicas de desempenho para apps mobile híbridas
FrontInBahia 2014: 10 dicas de desempenho para apps mobile híbridas
 
MIKE Stack Introduction - MongoDB, io.js, KendoUI, and Express
MIKE Stack Introduction - MongoDB, io.js, KendoUI, and ExpressMIKE Stack Introduction - MongoDB, io.js, KendoUI, and Express
MIKE Stack Introduction - MongoDB, io.js, KendoUI, and Express
 
WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...
 
#NewMeetup Performance
#NewMeetup Performance#NewMeetup Performance
#NewMeetup Performance
 
Practical HTML5: Using It Today
Practical HTML5: Using It TodayPractical HTML5: Using It Today
Practical HTML5: Using It Today
 
An Introduction to Tornado
An Introduction to TornadoAn Introduction to Tornado
An Introduction to Tornado
 
PHP and Rich Internet Applications
PHP and Rich Internet ApplicationsPHP and Rich Internet Applications
PHP and Rich Internet Applications
 

Último

A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI AgeCprime
 
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...AliaaTarek5
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfNeo4j
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityIES VE
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationKnoldus Inc.
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPathCommunity
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesThousandEyes
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsRavi Sanghani
 
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Scott Andery
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality AssuranceInflectra
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rick Flair
 

Último (20)

A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI Age
 
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdf
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a reality
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog Presentation
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to Hero
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and Insights
 
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...
 

Building a real life application in node js

  • 1. Building a real-life application in Node JS Darren Waddell
  • 2. ME ME ME ME ME • MooTools Developer • Love JavaScript! • C# Developer • Love building big apps!
  • 4. ‘Real-life applications’ • Websites • Content Management Systems • Blog Engines • (Not games, chat programs, ‘Native HTML5’ fish demos)
  • 6. What did I need to start • OSX! (or linux) • Install Node and NPM • A DB (MongoDB)
  • 7. Confusing things! • Non-blocking, event driven, asynchronous • NoSQL • Modules and NPM • No Firebug!
  • 8. Things I need for my app • Routing • Database • Templating
  • 9. Express Setting up server var app = require('express').createServer(); app.get('/', function(req, res){ res.send('hello world'); }); app.listen(80);
  • 10. Express Setting up View handler app.set('view engine', 'jade'); app.set('views', __dirname + '/views'); app.get('/foo/bar', function(req, res){ res.render('foo/bar'); // calls /views/foo/bar.jade }); app.listen(80);
  • 11. Express Setting up ‘static assets’ var app = require('express').createServer(); app.use( express.static(__dirname + '/public') ); <script type=”foo.js”></script> // is at http://foo.com/foo.js // NOT http://foo.com/public/foo.js
  • 12. Express Passing data to views app.get('/foo/bar', function(req, res){ res.render('foo/bar', { locals: { foo: ‘bar’ } }); });
  • 13. Express Passing data to views app.get('/users/:id', function(req, res){ // req.params contains // the querystring values var id = req.params.id; });
  • 14. Express Passing data to views app.use(express.bodyParser()); app.post('/users/:id', function(req, res){ // req.body contains the postback var username = req.body.name; });
  • 15. Express ‘Master Pages’ app.set('view options', { layout: 'shared/layout' }); app.get('/foo/bar', function(req, res){ res.render('foo/bar'); });
  • 16. Things I need for my app • Routing • Database • Templating
  • 17. Mongo DB • No tables! ‘Collections’ • No Rows! ‘Documents’ • No columns! ‘Fields’ • JSON format! • No SQL joins! • Flexible table collection structure
  • 18. Mongo DB select * from ‘foo’ db.foo.find({});
  • 19. Mongo DB insert into ‘foo’ set (‘foobar’) values (‘whatever’); db.foo.insert({ ‘foobar’: ‘whatever’ });
  • 20. Mongo DB delete from ‘foo’ where ‘name’ = ‘Darren’ db.foo.remove({ ‘name’:‘Darren’ });
  • 21. Mongoose • Models • Getters and Setters, Defaults,Validators • Avoid callback soup (very important!)
  • 22. Mongoose Simple modelling var mongoose = require(‘mongoose’); mongoose.connect(‘mongodb://localhost/myDB’); var User = new mongoose.Schema({ username: String, fullname: String, password: String }); var myUserModel = mongoose.model(‘User’); myUserModel.find({}, function(err, docs){ docs.forEach(function(user){ // do stuff }); });
  • 23. Mongoose Simple modelling var mongoose = require(‘mongoose’); mongoose.connect(‘mongodb://localhost/myDB’); var User = new mongoose.Schema({ username: String, fullname: String, password: String }); var myUserModel = mongoose.model(‘User’); myUserModel.username = ‘fakedarren’; myUserModel.fullname = ‘William Waddell’; myUserModel.save();
  • 24. Mongoose Simple modelling var myUserModel = mongoose.model(‘User’); myUserModel.username = ‘fakedarren’; myUserModel.fullname = ‘William Waddell’; myUserModel.save();
  • 25. MongooseDefault values var mongoose = require(‘mongoose’); mongoose.connect(‘mongodb://localhost/myDB’); var User = new mongoose.Schema({ username: String, fullname: String, password: String, role: { type: String, default: ‘Admin’ } });
  • 26. Mongoose Getters and Setters var mongoose = require(‘mongoose’); mongoose.connect(‘mongodb://localhost/myDB’); var User = new mongoose.Schema({ username: String, fullname: String, password: String }); User.path(‘password’).set(function(value){ if (password.length < 8){ return new Error(‘Password must be more than 8 characters’); } else { return value; } });
  • 27. Mongoose Middleware / promises / whatever it’s called User.pre(‘save’, function(next){ // do something next(); }); User.pre(‘save’, function(next){ // do something else next(); }); var myUserModel = mongoose.model(‘User’); myUserModel.username = ‘fakedarren’; myUserModel.fullname = ‘William Waddell’; myUserModel.save();
  • 28. Things I need for my app • Routing • Database • Templating
  • 29. View Engines HAML Jade EJS CoffeeKup jQuery Templates
  • 30. View Engines HAML Jade EJS CoffeeKup jQuery Templates
  • 31. Jade http://jade-lang.com/ !!! 5 html(lang="en") head title= pageTitle script(type='text/javascript') if (foo) { bar() } body h1 Jade - node template engine #container - if (youAreUsingJade) p You are amazing - else p Get on it!
  • 32. !!! 5 html(lang="en") head title= pageTitle script(type='text/javascript') if (foo) { bar() } body h1 Jade - node template engine #container - if (youAreUsingJade) p You are amazing - else p Get on it!
  • 33. EJS https://github.com/visionmedia/ejs <!DOCTYPE html> <html> <head> <title>Awesome</title> </head> <body> <% if (names.length) { %> <ul>     <% names.forEach(function(name){ %>       <li><%= name %></li>     <% }) %>   </ul> <% } %> </body> </html>
  • 34. <!DOCTYPE html> <html> <head> <title>Awesome</title> </head> <body> <% if (names.length) { %> <ul>     <% names.forEach(function(name){ %>       <li><%= name %></li>     <% }) %>   </ul> <% } %> </body> </html>
  • 35. Things I need for my app • Routing • Database • Templating
  • 36. Things I need for my app • Routing • Database • Templating • And a million other things....
  • 37. Thanks! @fakedarren https://github.com/fakedarren/node-cms

Notas do Editor

  1. \n
  2. \n
  3. \n
  4. \n
  5. \n
  6. \n
  7. \n
  8. \n
  9. \n
  10. \n
  11. \n
  12. \n
  13. \n
  14. \n
  15. \n
  16. \n
  17. \n
  18. \n
  19. \n
  20. \n
  21. \n
  22. \n
  23. \n
  24. \n
  25. \n
  26. \n
  27. \n
  28. \n
  29. \n
  30. \n
  31. \n
  32. \n
  33. \n
  34. \n
  35. \n
  36. \n
  37. \n