SlideShare ist ein Scribd-Unternehmen logo
1 von 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

Weitere ähnliche Inhalte

Was ist angesagt?

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
 

Was ist angesagt? (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
 

Andere mochten auch

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!
 

Andere mochten auch (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
 

Ähnlich wie 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
 

Ähnlich wie 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
 

Kürzlich hochgeladen

Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
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
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfhans926745
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
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
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
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
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
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
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
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
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 

Kürzlich hochgeladen (20)

Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
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
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
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...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
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
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
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
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
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
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 

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

Hinweis der Redaktion

  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