SlideShare ist ein Scribd-Unternehmen logo
1 von 67
Downloaden Sie, um offline zu lesen
NODE.JS ARCHITECTURE AND
GETTING STARTED WITH EXPRESS.JS
Jordan Kasper | Developer Evangelist
NODE.JS ARCHITECTURE
MODULARITY
MODULE PATTERNS
There are various patterns...
Simple Object API
Revealing Module (Function Initialization)
Object Constructor
SIMPLE OBJECT API
// lib/employee.js
module.exports = {
    salary: 50000,
    giveRaise: function( amount ) {
        salary += amount;
    }
};
Why not always use simple objects?
Modules are cached!
REVEALING MODULE PATTERN
module.exports = function createWorker( options ) {
    // Setup...
    return {
        salary: 50000,
        giveRaise: function( amount ) {
            this.salary += amount;
        }
    };
};
OBJECT CONSTRUCTOR PATTERN
var Worker = module.exports = function Worker( options ) {
    // ...
};
Worker.prototype.salary = 50000;
Worker.prototype.giveRaise = function( amount ) {
    this.salary += amount;
};
SCALING
VERTICAL SCALING
NODE CLUSTERING
var http = require('http'),
    cluster = require('cluster');
if (cluster.isMaster) {
    for (var i = 0; i < numCPUCores; i++) {
        cluster.fork();
    };
} else {
    http
        .createServer(function(req, res) {
            // ...
        })
        .listen(8080, ...);
});
USING A PROCESS MANAGER
Easy clustering and scaling without altering application
code
StrongLoop Process Manager (strong-pm)
PM2
Comparison Chart
Forever
LOAD BALANCING
cluster uses a simple round-robin approach...
...but there are better ways!
HORIZONTAL SCALING
HORIZONTAL SCALING
Nginx
BASIC NGINX CONFIG
server {
    listen 80
    location / {
        proxy_pass http://localhost:3000;
    }
    location /static/ {
        root /var/www/my­app/public;
    }
}
$ sudo service nginx start
NGINX LOAD BALANCER
http {
    upstream myapp {
        least_conn; # round­robin is the default...
                    # Or use ip_hash; for "sticky" sessions...
        server www1.my­app.com;
        server www2.my­app.com;
        server www3.my­app.com;
    }
    server {
        listen 80
        location / {
            proxy_pass http://myapp;
        }
    }
}
STRONGLOOP AND NGINX
If you're using strong-pm you can use the
!
StrongLoop nginx
controller
~$ npm install ­g strong­nginx­controller
~$ sl­nginx­ctl­install
Install the Controller on the load balancing host...
...then manage the load balancing infrastructure from
:StrongLoop Arc
SCALING WITH STRONGLOOP ARC
Nginx
EXPRESS.JS
EXPRESS.JS
Fast, light, unopinionated framework for web applications.
EXPRESS HELLO WORLD
~/my­app$ npm init
...
~/my­app$ npm install express ­­save
EXPRESS HELLO WORLD
// in app.js
var express = require('express');
var myApp = express();
myApp.get('/', function handleRoot(req, res, next) {
    res.send('Hello World!');
});
myApp.listen(8080);
~/my­app$ node app.js
SCAFFOLDING AN EXPRESS APP
SCAFFOLDING EXPRESS
Install the CLI generator first...
~$ npm install ­g express­generator
~$ express my­app
...
~$ cd my­app
~/my­app$ npm install
A SCAFFOLDED APP
my­app/
 |_ bin            # execution file (shell script)
 |_ node_modules
 |_ public         # images, css, fonts, etc
 |_ routes         # Node.js routing code
 |_ views          # server­side templates
 |_ app.js
 |_ package.json
RUNNING A SCAFFOLDED APP
~/my­app$ npm start
{
  ...,
  "scripts": {
    "start": "node ./bin/www"
  },
  ...
CONFIGURING EXPRESS
CONFIGURING EXPRESS
var app = express();
app.set('views', 'views');
app.set('view engine', 'jade');
app.set('port', process.env.PORT || 3000);
app.set('foo', 'bar');
server.listen( app.get('port') );
REQUEST ROUTING
BASIC ROUTING
var express = require('express');
var myApp = express();
myApp.get('/', function handleRoot(req, res, next) {
    res.send('Hello World!');
});
myApp.listen( 3000 );
POST ROUTING
myApp.post('/user', function createUser(req, res, next) {
    // Create the user record...
    res.redirect('/my­account');
});
POST ROUTING
myApp.post('/user', function createUser(req, res, next) {
    // Create the user record...
    // Where do we get the data from?
    res.redirect('/my­account');
});
MIDDLEWARE
MIDDLEWARE EXAMPLES
var express = require('express'),
    bodyParser = require('body­parser');
var app = express();
// app config...
// Parse POST form data...
app.use( bodyParser.urlencoded({ extended: false }) );
app.post('/user', function createUser() {
    var user = {
        username: req.body.username,
        ...
    };
    ...
});
ORDER MATTERS!
Middleware are executed in the order specified
app.use( express.logger('dev') );
app.use( myAuthModule() );
app.use( bodyParser.json() );
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'public')));
// Routing middleware...
MIDDLEWARE - WHEN DOES IT END?
Middleware processing ends when next() is not called
(or an error is generated)
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.get('/about', function aboutUs(req, res, next) {
    res.send('We are StrongLoop!');
    // no call to next()
});
app.get('/user', ...);
CUSTOM MIDDLEWARE
app.use(function (req, res, next) {
    // Do some work...
    // Modify the req or res...
    // execute the callback when done
    next();
});
CUSTOM MIDDLEWARE - ERRORS
app.use(function (req, res, next) {
    // do something...
    if (thereWasAnError) {
        var err = new Error(' ... ');
        next( err );
        return;
    }
    // No error, so we proceed...
    next();
});
HANDLING MIDDLEWARE ERRORS
app.use(function(err, req, res, next) {
    // Do whatever you need to...
    if (err.code === 404) {
        res.redirect('/error­404');
    } else {
        // Or you can keep processing this (or a new) Error
        next(err);
    }
});
HANDLING MIDDLEWARE ERRORS
Always set up a "catchall" error handler!
SERVER-SIDE TEMPLATING
TEMPLATES
Small blocks that we can plug data into at run-time
//­ /views/index.jade
doctype html
html
    head
        title #{title}
    body
        section.main­body.clear
            #{homepageText}
TEMPLATING ENGINE
~/my­app$ npm install ­­save jade
var app = express();
app.set('views', 'views');
app.set('view engine', 'jade');
USING A TEMPLATE
app.get('/' function handleRoot(req, res, next) {
    res.render('index', {
        title: 'StrongLoop ­ Home',
        homepageText: 'We all love StrongLoop!'
    });
});
DON'T FORGET YOUR MODULARITY!
NOT MODULAR...
var express = require('express'),
    bodyParser = require('body­parser');
var app = express();
// app config and other middleware...
app.post('/user', function createUser() {
    var user = {
        username: req.body.username,
        ...
    };
    db.create(user, function() {
        res.render('user/my­account', { ... });
    });
});
THE 4.0 ROUTER INTERFACE
// in routes/users.js
var express = require('express');
var router = express.Router();
router.get('/', function(req, res, next) {
  // Get a list of users...
  res.render('user/list', { results: users });
});
router.get('/:id', function(req, res, next) {
  // Get a single user...
  res.render('user/my­account', { user: user });
});
router.post('/', function(req, res, next) {
  // Create a user...
  res.redirect('user/my­account', { user: user });
});
module.exports = router;
THE 4.0 ROUTER INTERFACE
// in app.js
var express = require('express'),
    ...;
var app = express();
// app config and middleware...
app.use('/users', require('./routes/users'));
REQUEST OBJECT
QUERY PARAMETERS
app.get('/users', function (req, res, next) {
    var limit = req.query.limit || 10,
        users = [];
    // Retrieve all users...
    res.render('user/list', {
        results: users,
        nextIndex: 11
    });
});
URL PARAMETERS
app.get('/users/:id', function (req, res, next) {
    var id = req.params.id,
        user = null;
    // Retrieve a single user...
    if (req.xhr) {
        res.json({ user: user });
    } else {
        res.render('user/single', {
            user: user
        });
    }
});
URL PARAMETERS
app.get(/^/users/(d+)$/, function (req, res, next) {
    var id = req.params[0],
        user = null;
    // Retrieve a single user...
    // ...
});
RESPONSE OBJECT
RESPONSE METHODS
response.send(data) or response.end(data)
response.status(httpStatus)
response.send(201, someData)
response.sendfile('path/to/someFile.json')
response.download('/report-12345.pdf')
HTTP STATUS CODES
2XX: for successfully processed requests
3XX: for redirections or cache information
4XX: for client-side errors
5XX: for server-side errors
QUESTIONS?
NODE.JS ARCHITECTURE AND
GETTING STARTED WITH EXPRESS.JS
Jordan Kasper | Developer Evangelist
Join us for more events!
strongloop.com/developers/events

Weitere ähnliche Inhalte

Was ist angesagt?

Was ist angesagt? (20)

What Is Express JS?
What Is Express JS?What Is Express JS?
What Is Express JS?
 
Angular 4 The new Http Client Module
Angular 4 The new Http Client ModuleAngular 4 The new Http Client Module
Angular 4 The new Http Client Module
 
Basic Concept of Node.js & NPM
Basic Concept of Node.js & NPMBasic Concept of Node.js & NPM
Basic Concept of Node.js & NPM
 
Intro to React
Intro to ReactIntro to React
Intro to React
 
Unit 1 - TypeScript & Introduction to Angular CLI.pptx
Unit 1 - TypeScript & Introduction to Angular CLI.pptxUnit 1 - TypeScript & Introduction to Angular CLI.pptx
Unit 1 - TypeScript & Introduction to Angular CLI.pptx
 
Angular 2.0 forms
Angular 2.0 formsAngular 2.0 forms
Angular 2.0 forms
 
Introduction to AngularJS
Introduction to AngularJSIntroduction to AngularJS
Introduction to AngularJS
 
NodeJS guide for beginners
NodeJS guide for beginnersNodeJS guide for beginners
NodeJS guide for beginners
 
Angular Data Binding
Angular Data BindingAngular Data Binding
Angular Data Binding
 
Build RESTful API Using Express JS
Build RESTful API Using Express JSBuild RESTful API Using Express JS
Build RESTful API Using Express JS
 
Nodejs functions & modules
Nodejs functions & modulesNodejs functions & modules
Nodejs functions & modules
 
Angular
AngularAngular
Angular
 
Nodejs Explained with Examples
Nodejs Explained with ExamplesNodejs Explained with Examples
Nodejs Explained with Examples
 
Javascript this keyword
Javascript this keywordJavascript this keyword
Javascript this keyword
 
Spring Boot and REST API
Spring Boot and REST APISpring Boot and REST API
Spring Boot and REST API
 
JavaScript Tutorial
JavaScript  TutorialJavaScript  Tutorial
JavaScript Tutorial
 
Angular Notes.pdf
Angular Notes.pdfAngular Notes.pdf
Angular Notes.pdf
 
JavaScript
JavaScriptJavaScript
JavaScript
 
Introduction to TypeScript
Introduction to TypeScriptIntroduction to TypeScript
Introduction to TypeScript
 
React js
React jsReact js
React js
 

Andere mochten auch

Node.js Enterprise Middleware
Node.js Enterprise MiddlewareNode.js Enterprise Middleware
Node.js Enterprise Middleware
Behrad Zari
 
Node js presentation
Node js presentationNode js presentation
Node js presentation
martincabrera
 

Andere mochten auch (18)

Nodejs intro
Nodejs introNodejs intro
Nodejs intro
 
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
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
Npm
NpmNpm
Npm
 
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
 
Node.js Workshop - Sela SDP 2015
Node.js Workshop  - Sela SDP 2015Node.js Workshop  - Sela SDP 2015
Node.js Workshop - Sela SDP 2015
 
Node.js Enterprise Middleware
Node.js Enterprise MiddlewareNode.js Enterprise Middleware
Node.js Enterprise Middleware
 
Node ppt
Node pptNode ppt
Node ppt
 
Node.js architecture (EN)
Node.js architecture (EN)Node.js architecture (EN)
Node.js architecture (EN)
 
NodeJS - Server Side JS
NodeJS - Server Side JS NodeJS - Server Side JS
NodeJS - Server Side JS
 
Introduction to NPM and building CLI Tools with Node.js
Introduction to NPM and building CLI Tools with Node.jsIntroduction to NPM and building CLI Tools with Node.js
Introduction to NPM and building CLI Tools with Node.js
 
Node js presentation
Node js presentationNode js presentation
Node js presentation
 
Architecting large Node.js applications
Architecting large Node.js applicationsArchitecting large Node.js applications
Architecting large Node.js applications
 
Introduction to Angularjs
Introduction to AngularjsIntroduction to Angularjs
Introduction to Angularjs
 
Best Practices for Getting Started with AWS
Best Practices for Getting Started with AWSBest Practices for Getting Started with AWS
Best Practices for Getting Started with AWS
 
MySql slides (ppt)
MySql slides (ppt)MySql slides (ppt)
MySql slides (ppt)
 
Moodle.ppt
Moodle.pptMoodle.ppt
Moodle.ppt
 
Node.js - Best practices
Node.js  - Best practicesNode.js  - Best practices
Node.js - Best practices
 

Ähnlich wie Node Architecture and Getting Started with 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...
Fabio Franzini
 
JavaScript (without DOM)
JavaScript (without DOM)JavaScript (without DOM)
JavaScript (without DOM)
Piyush Katariya
 

Ähnlich wie Node Architecture and Getting Started with Express (20)

Javascript Design Patterns
Javascript Design PatternsJavascript Design Patterns
Javascript Design Patterns
 
Advance JS and oop
Advance JS and oopAdvance JS and oop
Advance JS and oop
 
Javascript Module Patterns
Javascript Module PatternsJavascript Module Patterns
Javascript Module Patterns
 
Building Reusable Custom Elements With Angular
Building Reusable Custom Elements With AngularBuilding Reusable Custom Elements With Angular
Building Reusable Custom Elements With Angular
 
Heroku pop-behind-the-sense
Heroku pop-behind-the-senseHeroku pop-behind-the-sense
Heroku pop-behind-the-sense
 
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...
 
JavaScript (without DOM)
JavaScript (without DOM)JavaScript (without DOM)
JavaScript (without DOM)
 
Front End Development: The Important Parts
Front End Development: The Important PartsFront End Development: The Important Parts
Front End Development: The Important Parts
 
Single Page Applications on JavaScript and ASP.NET MVC4
Single Page Applications on JavaScript and ASP.NET MVC4Single Page Applications on JavaScript and ASP.NET MVC4
Single Page Applications on JavaScript and ASP.NET MVC4
 
Writing HTML5 Web Apps using Backbone.js and GAE
Writing HTML5 Web Apps using Backbone.js and GAEWriting HTML5 Web Apps using Backbone.js and GAE
Writing HTML5 Web Apps using Backbone.js and GAE
 
How AngularJS Embraced Traditional Design Patterns
How AngularJS Embraced Traditional Design PatternsHow AngularJS Embraced Traditional Design Patterns
How AngularJS Embraced Traditional Design Patterns
 
Angular.js is super cool
Angular.js is super coolAngular.js is super cool
Angular.js is super cool
 
Uncommon Design Patterns
Uncommon Design PatternsUncommon Design Patterns
Uncommon Design Patterns
 
Metaprogramming in ES6
Metaprogramming in ES6Metaprogramming in ES6
Metaprogramming in ES6
 
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
 
meet.js - QooXDoo
meet.js - QooXDoomeet.js - QooXDoo
meet.js - QooXDoo
 
Backbone js
Backbone jsBackbone js
Backbone js
 
Object Oriented Programming In JavaScript
Object Oriented Programming In JavaScriptObject Oriented Programming In JavaScript
Object Oriented Programming In JavaScript
 
Module design pattern i.e. express js
Module design pattern i.e. express jsModule design pattern i.e. express js
Module design pattern i.e. express js
 
Unity 2018からのハイパフォーマンスな機能紹介
Unity 2018からのハイパフォーマンスな機能紹介Unity 2018からのハイパフォーマンスな機能紹介
Unity 2018からのハイパフォーマンスな機能紹介
 

Kürzlich hochgeladen

CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
VictorSzoltysek
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
mohitmore19
 

Kürzlich hochgeladen (20)

Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfAzure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 

Node Architecture and Getting Started with Express