SlideShare una empresa de Scribd logo
1 de 40
Descargar para leer sin conexión
Vitaliy Basyuk aka Wolfgang Bas
becevka@kucoe.net
Express Nodes on the
right Angle
Did you ever have a product idea?
A dream will always triumph over reality, once it is given the
chance. Stanislaw Lem
birkey.com
My way on finding technologies which help not to lose excitement of my idea
and not let me sink in the sea of boilerplate code.
Node.js is a platform built on Chrome's JavaScript runtime for
easily building fast, scalable network applications.
The basic philosophy of node.js is
●
Non-blocking I/O
Every I/O call must take a callback, whether it is to retrieve information from
disk, network or another process
●
Built-in support for the most important protocols
HTTP, DNS, TLS
●
Low-level
Does not remove functionality present at the POSIX layer. For example,
support half-closed TCP connections.
●
Stream everything
Never force the buffering of data
Code
fs.readFile('/etc/passwd', function(err, data){
console.log(data);
});
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello Worldn');
}).listen(8081);
console.log('Server running at port 8081');
Server routing
var http = require('http');
http.createServer(function (req, res) {
var path = url.parse(req.url).pathname;
var hello = {message: "Hello, world"};
switch (path) {
case '/json':
res.writeHead(200, {'Content-Type':'application/json; charset=UTF-
8'});
res.end(JSON.stringify(hello));
break;
default:
res.writeHead(404, {'Content-Type': 'text/html; charset=UTF-8'});
res.end('Sorry, we cannot find that!');
}
}).listen(8081);
Express
var express = require('express');
var app = express();
app.get('/', function(req, res){
res.send('Hello World');
});
app.listen(8081);
var express = require('express');
var app = express();
var hello = {message: "Hello, world"};
app.get('/json', function(req, res){
res.json(hello);
});
app.all('*', function(req, res){
res.send(404, 'Sorry, we cannot find that!');
});
app.listen(8081);
What Express does?
●
Processing request parameters and headers
●
Routing
●
Rendering response and views support
●
Application configuration and middleware
support
session, CSRF, basicAuth, vhost, static content, custom
Express example
var express = require('express'),
routes = require('./routes'),
api = require('./routes/api');
var app = express();
app.configure(function(){
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.static(__dirname + '/public'));
app.use(app.router);
});
app.configure('development', function(){
app.use(express.errorHandler({ dumpExceptions: true,
showStack: true }));
});
app.configure('production', function(){
app.use(express.errorHandler());
});
Express example (continue)
app.get('/', routes.index);
// res.render('index');
app.get('/posts', api.posts);
app.get('/posts/:id', api.post);
//var id = req.params.id;
app.post('/posts', api.addPost);
//res.json(req.body);
app.put('/posts/:id', api.editPost);
app.delete('/posts/:id', api.deletePost);
app.get('*', routes.index);
app.listen(3000, function(){
console.log("Express server listening on port %d in %s
mode", app.address().port, app.settings.env);
});
Node.js pros
●
Known language (JavaScript)
●
Additional API are documented well and understandable
●
Effortless building of REST services with Express
●
No server configuration, easy to install and run
●
Real-time application support
●
Quite big community and a lot of tools implemented
Node.js cons
●
Not mature enough and some API are not stable
●
Running on production server might differ
●
Not enough tools and libraries
●
Not for a CPU consuming routines
●
Async code looks not so pretty
Further reading
http://nodejs.org/api/ - Node.js official API
http://book.mixu.net/ - Mixu Node book
http://ofps.oreilly.com/titles/9781449398583/index.html - Node Up and Running
(has chapter on Express)
http://expressjs.com/api.html - Express API
Useful modules
http://socket.io/ - for realtime apps
https://github.com/visionmedia/jade - Express template engine
http://visionmedia.github.io/mocha/ - test framework
http://chaijs.com/ - BDD/TDD assertion library
MongoDB
Document-Oriented Storage for JSON-style documents with
dynamic schemas, full index support and rich document-
based queries.
db.articles.find({'comments.0.by':'becevka'})
Mongoskin
var mongo = require('mongoskin');
var db = mongo.db('localhost:27017/test?auto_reconnect');
db.bind('posts', {
removeTagWith : function (tag, fn) {
this.remove({tags:tag},fn);
}
});
db.posts.removeTagWith('delete', function (err, replies){
//do something
});
Tim (Berners-Lee) bawled me out in the summer of '93 for
adding images to the thing Marc Andreesen, Mosaic
Requirements for UI framework

Declarative, simple way to describe our
presentation, how it looks and how it lays out

Dynamic application out of the box

No need to extend framework classes in order
to make it work

Easy implemented REST support

Less code
<label>Here is your value:</label>
<input type="text" name="value"/>
<span>Here is double: {{value * 2}}</span>
Core Features of AngularJS

Two Way Data-binding

Model View Whatever

HTML Templates

Deep Linking

Dependency Injection

Directives
Two Way Data-Binding
Two Way Data-Binding
<span id="yourName"></span>
document.getElementById('yourName')[0].text = 'bob';
<span>{{yourName}}</span>
var yourName = 'bob';
Model View Whatever
HTML Templates
<div ng-controller="AlbumCtrl">
<ul>
<li ng-repeat="image in images">
<img ng-src="{{image.thumbnail}}" alt="{{image.description}}">
</li>
</ul>
</div>
function AlbumCtrl($scope) {
scope.images = [
{"thumbnail":"img/image_01.png", "description":"Image 01
description"},
{"thumbnail":"img/image_02.png", "description":"Image 02
description"},
{"thumbnail":"img/image_03.png", "description":"Image 03
description"},
{"thumbnail":"img/image_04.png", "description":"Image 04
description"},
{"thumbnail":"img/image_05.png", "description":"Image 05
description"}
];
}
Deep Linking
Dependency Injection
function EditCtrl($scope, $location, $routeParams, User) {
// Something clever here...
}
Directives
<div class="container">
<div class="inner">
<ul>
<li>Item
<div class="subsection">item 2</div>
</li>
</ul>
</div>
</div>
<dropdown>
<item>Item 1
<subitem>Item 2</subitem>
</item>
</dropdown>
Other features
Filters
<td>{{name|uppercase}}</td>
Routes
app.config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/login', {
templateUrl: 'partials/login',
controller: LoginCtrl
});
}]);
Services
app.factory('User', function ($resource) {
var User = $resource('/users/:_id', {}, {
update: { method: 'PUT', params: {_id: "@_id" }}
});
return User;
});
Complete example
<html ng-app='myApp'>
<head>
<title>Your Shopping Cart</title>
</head>
<body ng-controller='CartController'>
<h1>Your Order</h1>
<div ng-repeat='item in items'>
<span>{{item.title}}</span>
<input ng-model='item.quantity'>
<span>{{item.price | currency}}</span>
<span>{{item.price * item.quantity | currency}}</span>
<button ng-click="remove($index)">Remove</button>
</div>
<script src="angular.js"> </script>
<script>
angular.module("myApp", []);
function CartController($scope) {
$scope.items = [
{title: 'Paint pots', quantity: 8, price: 3.95},
{title: 'Polka dots', quantity: 17, price: 12.95},
{title: 'Pebbles', quantity: 5, price: 6.95}
];
$scope.remove = function(index) {
$scope.items.splice(index, 1);
}
}
</script>
</body>
</html>
Angular Resources

http://angular-ui.github.io/ - a lot of useful directives and
filters

http://angular-ui.github.io/bootstrap/ - twitter bootstrap
directives

http://angular-ui.github.io/ng-grid/ - grid

https://github.com/angular/angularjs-batarang - web
inspector extension

http://docs.angularjs.org/ - official documentation

http://www.egghead.io/ - video tutorials

http://deansofer.com/posts/view/14/AngularJs-Tips-and-
Tricks-UPDATED - Tips and tricks

http://www.cheatography.com/proloser/cheat-
sheets/angularjs/ - Cheat sheets
All together now
Amigo - AngularJS MongoDB Express Node.js project
generator. Allows easily scaffold project layout with CRUD
operations and UI skeleton.
https://github.com/becevka/amigo
$ npm install -g amigo
amigo todo
Amigo features

Resources scaffolding

MongoDB storage

Angular Routes

Angular Resources Factories

CRUD UI out of the box

Authentification

Session support and storing
Demo
Thanks
http://becevka.github.io/amigo/

Más contenido relacionado

La actualidad más candente

Single Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and JasmineSingle Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and Jasmine
Paulo Ragonha
 
Introducing Rendr: Run your Backbone.js apps on the client and server
Introducing Rendr: Run your Backbone.js apps on the client and serverIntroducing Rendr: Run your Backbone.js apps on the client and server
Introducing Rendr: Run your Backbone.js apps on the client and server
Spike Brehm
 
Angular를 활용한 웹 프론트단 개발과 2.0에서 달라진점
Angular를 활용한 웹 프론트단 개발과 2.0에서 달라진점Angular를 활용한 웹 프론트단 개발과 2.0에서 달라진점
Angular를 활용한 웹 프론트단 개발과 2.0에서 달라진점
Jeado Ko
 

La actualidad más candente (20)

How to Build SPA with Vue Router 2.0
How to Build SPA with Vue Router 2.0How to Build SPA with Vue Router 2.0
How to Build SPA with Vue Router 2.0
 
Single Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and JasmineSingle Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and Jasmine
 
An Introduction To Testing In AngularJS Applications
An Introduction To Testing In AngularJS Applications An Introduction To Testing In AngularJS Applications
An Introduction To Testing In AngularJS Applications
 
Advanced Tips & Tricks for using Angular JS
Advanced Tips & Tricks for using Angular JSAdvanced Tips & Tricks for using Angular JS
Advanced Tips & Tricks for using Angular JS
 
Backbone js
Backbone jsBackbone js
Backbone js
 
Workshop 12: AngularJS Parte I
Workshop 12: AngularJS Parte IWorkshop 12: AngularJS Parte I
Workshop 12: AngularJS Parte I
 
Workshop 27: Isomorphic web apps with ReactJS
Workshop 27: Isomorphic web apps with ReactJSWorkshop 27: Isomorphic web apps with ReactJS
Workshop 27: Isomorphic web apps with ReactJS
 
Building a js widget
Building a js widgetBuilding a js widget
Building a js widget
 
Symfony2 and AngularJS
Symfony2 and AngularJSSymfony2 and AngularJS
Symfony2 and AngularJS
 
AngularJs
AngularJsAngularJs
AngularJs
 
AngularJS Basics with Example
AngularJS Basics with ExampleAngularJS Basics with Example
AngularJS Basics with Example
 
Planbox Backbone MVC
Planbox Backbone MVCPlanbox Backbone MVC
Planbox Backbone MVC
 
Introducing Rendr: Run your Backbone.js apps on the client and server
Introducing Rendr: Run your Backbone.js apps on the client and serverIntroducing Rendr: Run your Backbone.js apps on the client and server
Introducing Rendr: Run your Backbone.js apps on the client and server
 
Dynamic Application Development by NodeJS ,AngularJS with OrientDB
Dynamic Application Development by NodeJS ,AngularJS with OrientDBDynamic Application Development by NodeJS ,AngularJS with OrientDB
Dynamic Application Development by NodeJS ,AngularJS with OrientDB
 
AngularJS Directives
AngularJS DirectivesAngularJS Directives
AngularJS Directives
 
Vue business first
Vue business firstVue business first
Vue business first
 
Angular를 활용한 웹 프론트단 개발과 2.0에서 달라진점
Angular를 활용한 웹 프론트단 개발과 2.0에서 달라진점Angular를 활용한 웹 프론트단 개발과 2.0에서 달라진점
Angular를 활용한 웹 프론트단 개발과 2.0에서 달라진점
 
Viking academy backbone.js
Viking academy  backbone.jsViking academy  backbone.js
Viking academy backbone.js
 
The JavaFX Ecosystem
The JavaFX EcosystemThe JavaFX Ecosystem
The JavaFX Ecosystem
 
Ajax Security
Ajax SecurityAjax Security
Ajax Security
 

Destacado

Joomla 3. Що нового для розробників у новій версії - Віталій Маренков
Joomla 3. Що нового для розробників у новій версії - Віталій МаренковJoomla 3. Що нового для розробників у новій версії - Віталій Маренков
Joomla 3. Що нового для розробників у новій версії - Віталій Маренков
Igor Bronovskyy
 

Destacado (8)

03 - chomu prohramisty ne testuiut - yurii chulovskyi - it event 2013 (5)
03 -  chomu prohramisty ne testuiut - yurii chulovskyi - it event 2013 (5)03 -  chomu prohramisty ne testuiut - yurii chulovskyi - it event 2013 (5)
03 - chomu prohramisty ne testuiut - yurii chulovskyi - it event 2013 (5)
 
15 - sphinx - efektyvnyi povnotekstovyi poshuk - marian koreniuk - it event 2...
15 - sphinx - efektyvnyi povnotekstovyi poshuk - marian koreniuk - it event 2...15 - sphinx - efektyvnyi povnotekstovyi poshuk - marian koreniuk - it event 2...
15 - sphinx - efektyvnyi povnotekstovyi poshuk - marian koreniuk - it event 2...
 
12 - gradle. evoliutsiia system avtomatychnoi zbirky - sviatoslav babych - it...
12 - gradle. evoliutsiia system avtomatychnoi zbirky - sviatoslav babych - it...12 - gradle. evoliutsiia system avtomatychnoi zbirky - sviatoslav babych - it...
12 - gradle. evoliutsiia system avtomatychnoi zbirky - sviatoslav babych - it...
 
Joomla 3. Що нового для розробників у новій версії - Віталій Маренков
Joomla 3. Що нового для розробників у новій версії - Віталій МаренковJoomla 3. Що нового для розробників у новій версії - Віталій Маренков
Joomla 3. Що нового для розробників у новій версії - Віталій Маренков
 
Протокол IP v.6: кожному по 300 млн. IP адрес - Сергій Шуляр
Протокол  IP v.6: кожному по 300 млн. IP адрес - Сергій ШулярПротокол  IP v.6: кожному по 300 млн. IP адрес - Сергій Шуляр
Протокол IP v.6: кожному по 300 млн. IP адрес - Сергій Шуляр
 
01 an environment for application development tools that help you keep it t...
01   an environment for application development tools that help you keep it t...01   an environment for application development tools that help you keep it t...
01 an environment for application development tools that help you keep it t...
 
11 - rozrobka prohramnoho zabezpechennia dlia vbudovanykh system - dmytro and...
11 - rozrobka prohramnoho zabezpechennia dlia vbudovanykh system - dmytro and...11 - rozrobka prohramnoho zabezpechennia dlia vbudovanykh system - dmytro and...
11 - rozrobka prohramnoho zabezpechennia dlia vbudovanykh system - dmytro and...
 
07 - vysnovky z tdd, pohliad pochatkivtsia - vitalii zinchenko it event 2013...
07 -  vysnovky z tdd, pohliad pochatkivtsia - vitalii zinchenko it event 2013...07 -  vysnovky z tdd, pohliad pochatkivtsia - vitalii zinchenko it event 2013...
07 - vysnovky z tdd, pohliad pochatkivtsia - vitalii zinchenko it event 2013...
 

Similar a 09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)

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
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applications
Tom Croucher
 
Practical AngularJS
Practical AngularJSPractical AngularJS
Practical AngularJS
Wei Ru
 
Cloud Endpoints _Polymer_ Material design by Martin Görner
Cloud Endpoints_Polymer_Material design by Martin GörnerCloud Endpoints_Polymer_Material design by Martin Görner
Cloud Endpoints _Polymer_ Material design by Martin Görner
European Innovation Academy
 
#NewMeetup Performance
#NewMeetup Performance#NewMeetup Performance
#NewMeetup Performance
Justin Cataldo
 

Similar a 09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5) (20)

soft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.jssoft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.js
 
Javascript first-class citizenery
Javascript first-class citizeneryJavascript first-class citizenery
Javascript first-class citizenery
 
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...
 
AngularJS Mobile Warsaw 20-10-2014
AngularJS Mobile Warsaw 20-10-2014AngularJS Mobile Warsaw 20-10-2014
AngularJS Mobile Warsaw 20-10-2014
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applications
 
Nodejs.meetup
Nodejs.meetupNodejs.meetup
Nodejs.meetup
 
Future Decoded - Node.js per sviluppatori .NET
Future Decoded - Node.js per sviluppatori .NETFuture Decoded - Node.js per sviluppatori .NET
Future Decoded - Node.js per sviluppatori .NET
 
General Principles of Web Security
General Principles of Web SecurityGeneral Principles of Web Security
General Principles of Web Security
 
Spine.js
Spine.jsSpine.js
Spine.js
 
Practical AngularJS
Practical AngularJSPractical AngularJS
Practical AngularJS
 
[Coscup 2012] JavascriptMVC
[Coscup 2012] JavascriptMVC[Coscup 2012] JavascriptMVC
[Coscup 2012] JavascriptMVC
 
Charla EHU Noviembre 2014 - Desarrollo Web
Charla EHU Noviembre 2014 - Desarrollo WebCharla EHU Noviembre 2014 - Desarrollo Web
Charla EHU Noviembre 2014 - Desarrollo Web
 
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
 
Cloud Endpoints _Polymer_ Material design by Martin Görner
Cloud Endpoints_Polymer_Material design by Martin GörnerCloud Endpoints_Polymer_Material design by Martin Görner
Cloud Endpoints _Polymer_ Material design by Martin Görner
 
前端概述
前端概述前端概述
前端概述
 
Bonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node jsBonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node js
 
Event-driven IO server-side JavaScript environment based on V8 Engine
Event-driven IO server-side JavaScript environment based on V8 EngineEvent-driven IO server-side JavaScript environment based on V8 Engine
Event-driven IO server-side JavaScript environment based on V8 Engine
 
Backbone js in drupal core
Backbone js in drupal coreBackbone js in drupal core
Backbone js in drupal core
 
Refresh Austin - Intro to Dexy
Refresh Austin - Intro to DexyRefresh Austin - Intro to Dexy
Refresh Austin - Intro to Dexy
 
#NewMeetup Performance
#NewMeetup Performance#NewMeetup Performance
#NewMeetup Performance
 

Último

Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
PECB
 

Último (20)

Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-IIFood Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Asian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptxAsian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptx
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
Role Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptxRole Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptx
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 

09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)

  • 1. Vitaliy Basyuk aka Wolfgang Bas becevka@kucoe.net Express Nodes on the right Angle
  • 2. Did you ever have a product idea?
  • 3. A dream will always triumph over reality, once it is given the chance. Stanislaw Lem
  • 5. My way on finding technologies which help not to lose excitement of my idea and not let me sink in the sea of boilerplate code.
  • 6.
  • 7. Node.js is a platform built on Chrome's JavaScript runtime for easily building fast, scalable network applications.
  • 8. The basic philosophy of node.js is ● Non-blocking I/O Every I/O call must take a callback, whether it is to retrieve information from disk, network or another process ● Built-in support for the most important protocols HTTP, DNS, TLS ● Low-level Does not remove functionality present at the POSIX layer. For example, support half-closed TCP connections. ● Stream everything Never force the buffering of data
  • 9. Code fs.readFile('/etc/passwd', function(err, data){ console.log(data); }); var http = require('http'); http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello Worldn'); }).listen(8081); console.log('Server running at port 8081');
  • 10. Server routing var http = require('http'); http.createServer(function (req, res) { var path = url.parse(req.url).pathname; var hello = {message: "Hello, world"}; switch (path) { case '/json': res.writeHead(200, {'Content-Type':'application/json; charset=UTF- 8'}); res.end(JSON.stringify(hello)); break; default: res.writeHead(404, {'Content-Type': 'text/html; charset=UTF-8'}); res.end('Sorry, we cannot find that!'); } }).listen(8081);
  • 11. Express var express = require('express'); var app = express(); app.get('/', function(req, res){ res.send('Hello World'); }); app.listen(8081); var express = require('express'); var app = express(); var hello = {message: "Hello, world"}; app.get('/json', function(req, res){ res.json(hello); }); app.all('*', function(req, res){ res.send(404, 'Sorry, we cannot find that!'); }); app.listen(8081);
  • 12. What Express does? ● Processing request parameters and headers ● Routing ● Rendering response and views support ● Application configuration and middleware support session, CSRF, basicAuth, vhost, static content, custom
  • 13. Express example var express = require('express'), routes = require('./routes'), api = require('./routes/api'); var app = express(); app.configure(function(){ app.set('views', __dirname + '/views'); app.set('view engine', 'jade'); app.use(express.bodyParser()); app.use(express.methodOverride()); app.use(express.static(__dirname + '/public')); app.use(app.router); }); app.configure('development', function(){ app.use(express.errorHandler({ dumpExceptions: true, showStack: true })); }); app.configure('production', function(){ app.use(express.errorHandler()); });
  • 14. Express example (continue) app.get('/', routes.index); // res.render('index'); app.get('/posts', api.posts); app.get('/posts/:id', api.post); //var id = req.params.id; app.post('/posts', api.addPost); //res.json(req.body); app.put('/posts/:id', api.editPost); app.delete('/posts/:id', api.deletePost); app.get('*', routes.index); app.listen(3000, function(){ console.log("Express server listening on port %d in %s mode", app.address().port, app.settings.env); });
  • 15. Node.js pros ● Known language (JavaScript) ● Additional API are documented well and understandable ● Effortless building of REST services with Express ● No server configuration, easy to install and run ● Real-time application support ● Quite big community and a lot of tools implemented
  • 16. Node.js cons ● Not mature enough and some API are not stable ● Running on production server might differ ● Not enough tools and libraries ● Not for a CPU consuming routines ● Async code looks not so pretty
  • 17. Further reading http://nodejs.org/api/ - Node.js official API http://book.mixu.net/ - Mixu Node book http://ofps.oreilly.com/titles/9781449398583/index.html - Node Up and Running (has chapter on Express) http://expressjs.com/api.html - Express API Useful modules http://socket.io/ - for realtime apps https://github.com/visionmedia/jade - Express template engine http://visionmedia.github.io/mocha/ - test framework http://chaijs.com/ - BDD/TDD assertion library
  • 18.
  • 19. MongoDB Document-Oriented Storage for JSON-style documents with dynamic schemas, full index support and rich document- based queries. db.articles.find({'comments.0.by':'becevka'})
  • 20. Mongoskin var mongo = require('mongoskin'); var db = mongo.db('localhost:27017/test?auto_reconnect'); db.bind('posts', { removeTagWith : function (tag, fn) { this.remove({tags:tag},fn); } }); db.posts.removeTagWith('delete', function (err, replies){ //do something });
  • 21.
  • 22. Tim (Berners-Lee) bawled me out in the summer of '93 for adding images to the thing Marc Andreesen, Mosaic
  • 23. Requirements for UI framework  Declarative, simple way to describe our presentation, how it looks and how it lays out  Dynamic application out of the box  No need to extend framework classes in order to make it work  Easy implemented REST support  Less code
  • 24. <label>Here is your value:</label> <input type="text" name="value"/> <span>Here is double: {{value * 2}}</span>
  • 25.
  • 26. Core Features of AngularJS  Two Way Data-binding  Model View Whatever  HTML Templates  Deep Linking  Dependency Injection  Directives
  • 28. Two Way Data-Binding <span id="yourName"></span> document.getElementById('yourName')[0].text = 'bob'; <span>{{yourName}}</span> var yourName = 'bob';
  • 30. HTML Templates <div ng-controller="AlbumCtrl"> <ul> <li ng-repeat="image in images"> <img ng-src="{{image.thumbnail}}" alt="{{image.description}}"> </li> </ul> </div> function AlbumCtrl($scope) { scope.images = [ {"thumbnail":"img/image_01.png", "description":"Image 01 description"}, {"thumbnail":"img/image_02.png", "description":"Image 02 description"}, {"thumbnail":"img/image_03.png", "description":"Image 03 description"}, {"thumbnail":"img/image_04.png", "description":"Image 04 description"}, {"thumbnail":"img/image_05.png", "description":"Image 05 description"} ]; }
  • 32. Dependency Injection function EditCtrl($scope, $location, $routeParams, User) { // Something clever here... }
  • 33. Directives <div class="container"> <div class="inner"> <ul> <li>Item <div class="subsection">item 2</div> </li> </ul> </div> </div> <dropdown> <item>Item 1 <subitem>Item 2</subitem> </item> </dropdown>
  • 34. Other features Filters <td>{{name|uppercase}}</td> Routes app.config(['$routeProvider', function($routeProvider) { $routeProvider. when('/login', { templateUrl: 'partials/login', controller: LoginCtrl }); }]); Services app.factory('User', function ($resource) { var User = $resource('/users/:_id', {}, { update: { method: 'PUT', params: {_id: "@_id" }} }); return User; });
  • 35. Complete example <html ng-app='myApp'> <head> <title>Your Shopping Cart</title> </head> <body ng-controller='CartController'> <h1>Your Order</h1> <div ng-repeat='item in items'> <span>{{item.title}}</span> <input ng-model='item.quantity'> <span>{{item.price | currency}}</span> <span>{{item.price * item.quantity | currency}}</span> <button ng-click="remove($index)">Remove</button> </div> <script src="angular.js"> </script> <script> angular.module("myApp", []); function CartController($scope) { $scope.items = [ {title: 'Paint pots', quantity: 8, price: 3.95}, {title: 'Polka dots', quantity: 17, price: 12.95}, {title: 'Pebbles', quantity: 5, price: 6.95} ]; $scope.remove = function(index) { $scope.items.splice(index, 1); } } </script> </body> </html>
  • 36. Angular Resources  http://angular-ui.github.io/ - a lot of useful directives and filters  http://angular-ui.github.io/bootstrap/ - twitter bootstrap directives  http://angular-ui.github.io/ng-grid/ - grid  https://github.com/angular/angularjs-batarang - web inspector extension  http://docs.angularjs.org/ - official documentation  http://www.egghead.io/ - video tutorials  http://deansofer.com/posts/view/14/AngularJs-Tips-and- Tricks-UPDATED - Tips and tricks  http://www.cheatography.com/proloser/cheat- sheets/angularjs/ - Cheat sheets
  • 37. All together now Amigo - AngularJS MongoDB Express Node.js project generator. Allows easily scaffold project layout with CRUD operations and UI skeleton. https://github.com/becevka/amigo $ npm install -g amigo amigo todo
  • 38. Amigo features  Resources scaffolding  MongoDB storage  Angular Routes  Angular Resources Factories  CRUD UI out of the box  Authentification  Session support and storing
  • 39. Demo