09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
DESCRIPTION
09 - Express Nodes on the right Angle - Vitaliy Basyuk - IT Event 2013 (5) 60 вузлів під правильним кутом - миттєва розробка програмних додатків використовуючи Node.js + Express + MongoDB + AngularJS. Коли ми беремось за новий продукт, передусім ми думаємо про пристрасть, яка необхідна йому, щоб зробити користувача задоволеним і відданим нашому баченню. А що допомагає нам здобути прихильність користувачів? Очевидно, що окрім самої ідеї, також важлими будуть: зручний користувацький інтерфейс, взаємодія в реальному часі та прозора робота з даними. Ці три властивості ми можемо здобути використовучи ті чи інші засоби, проте, коли все лиш починається, набагато зручніше, якщо інструменти допомагають втілити бажане, а не відволікають від головної мети. Ми розглянемо процес розробки, використовуючи Node.js, Express, MongoDB та AngularJS як найбільш корисного поєднання для отримання вагомої переваги вже на старті вашого продукту. Віталій Басюк http://itevent.if.ua/lecture/express-nodes-right-angle-rapid-application-development-using-nodejs-express-mongodb-angularTRANSCRIPT
![Page 2: 09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)](https://reader034.vdocuments.us/reader034/viewer/2022050904/5480bd715906b5d76c8b45af/html5/thumbnails/2.jpg)
Did you ever have a product idea?
![Page 3: 09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)](https://reader034.vdocuments.us/reader034/viewer/2022050904/5480bd715906b5d76c8b45af/html5/thumbnails/3.jpg)
A dream will always triumph over reality, once it is given the
chance. Stanislaw Lem
![Page 4: 09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)](https://reader034.vdocuments.us/reader034/viewer/2022050904/5480bd715906b5d76c8b45af/html5/thumbnails/4.jpg)
birkey.com
![Page 5: 09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)](https://reader034.vdocuments.us/reader034/viewer/2022050904/5480bd715906b5d76c8b45af/html5/thumbnails/5.jpg)
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.
![Page 6: 09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)](https://reader034.vdocuments.us/reader034/viewer/2022050904/5480bd715906b5d76c8b45af/html5/thumbnails/6.jpg)
![Page 7: 09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)](https://reader034.vdocuments.us/reader034/viewer/2022050904/5480bd715906b5d76c8b45af/html5/thumbnails/7.jpg)
Node.js is a platform built on Chrome's JavaScript runtime for easily building fast, scalable network applications.
![Page 8: 09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)](https://reader034.vdocuments.us/reader034/viewer/2022050904/5480bd715906b5d76c8b45af/html5/thumbnails/8.jpg)
The basic philosophy of node.js is
● Non-blocking I/OEvery 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 protocolsHTTP, DNS, TLS
● Low-levelDoes not remove functionality present at the POSIX layer. For example,
support half-closed TCP connections.
● Stream everythingNever force the buffering of data
![Page 9: 09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)](https://reader034.vdocuments.us/reader034/viewer/2022050904/5480bd715906b5d76c8b45af/html5/thumbnails/9.jpg)
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 World\n');
}).listen(8081);console.log('Server running at port 8081');
![Page 10: 09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)](https://reader034.vdocuments.us/reader034/viewer/2022050904/5480bd715906b5d76c8b45af/html5/thumbnails/10.jpg)
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);
![Page 11: 09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)](https://reader034.vdocuments.us/reader034/viewer/2022050904/5480bd715906b5d76c8b45af/html5/thumbnails/11.jpg)
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);
![Page 12: 09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)](https://reader034.vdocuments.us/reader034/viewer/2022050904/5480bd715906b5d76c8b45af/html5/thumbnails/12.jpg)
What Express does?
● Processing request parameters and headers
● Routing
● Rendering response and views support
● Application configuration and middleware supportsession, CSRF, basicAuth, vhost, static content, custom
![Page 13: 09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)](https://reader034.vdocuments.us/reader034/viewer/2022050904/5480bd715906b5d76c8b45af/html5/thumbnails/13.jpg)
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());});
![Page 14: 09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)](https://reader034.vdocuments.us/reader034/viewer/2022050904/5480bd715906b5d76c8b45af/html5/thumbnails/14.jpg)
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);});
![Page 15: 09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)](https://reader034.vdocuments.us/reader034/viewer/2022050904/5480bd715906b5d76c8b45af/html5/thumbnails/15.jpg)
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
![Page 16: 09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)](https://reader034.vdocuments.us/reader034/viewer/2022050904/5480bd715906b5d76c8b45af/html5/thumbnails/16.jpg)
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
![Page 17: 09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)](https://reader034.vdocuments.us/reader034/viewer/2022050904/5480bd715906b5d76c8b45af/html5/thumbnails/17.jpg)
Further reading
http://nodejs.org/api/ - Node.js official APIhttp://book.mixu.net/ - Mixu Node bookhttp://ofps.oreilly.com/titles/9781449398583/index.html - Node Up and Running
(has chapter on Express)http://expressjs.com/api.html - Express API
Useful moduleshttp://socket.io/ - for realtime appshttps://github.com/visionmedia/jade - Express template enginehttp://visionmedia.github.io/mocha/ - test frameworkhttp://chaijs.com/ - BDD/TDD assertion library
![Page 18: 09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)](https://reader034.vdocuments.us/reader034/viewer/2022050904/5480bd715906b5d76c8b45af/html5/thumbnails/18.jpg)
![Page 19: 09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)](https://reader034.vdocuments.us/reader034/viewer/2022050904/5480bd715906b5d76c8b45af/html5/thumbnails/19.jpg)
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'})
![Page 20: 09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)](https://reader034.vdocuments.us/reader034/viewer/2022050904/5480bd715906b5d76c8b45af/html5/thumbnails/20.jpg)
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 });
![Page 21: 09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)](https://reader034.vdocuments.us/reader034/viewer/2022050904/5480bd715906b5d76c8b45af/html5/thumbnails/21.jpg)
![Page 22: 09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)](https://reader034.vdocuments.us/reader034/viewer/2022050904/5480bd715906b5d76c8b45af/html5/thumbnails/22.jpg)
Tim (Berners-Lee) bawled me out in the summer of '93 for adding images to the thing Marc Andreesen, Mosaic
![Page 23: 09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)](https://reader034.vdocuments.us/reader034/viewer/2022050904/5480bd715906b5d76c8b45af/html5/thumbnails/23.jpg)
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
![Page 24: 09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)](https://reader034.vdocuments.us/reader034/viewer/2022050904/5480bd715906b5d76c8b45af/html5/thumbnails/24.jpg)
<label>Here is your value:</label> <input type="text" name="value"/> <span>Here is double: {{value * 2}}</span>
![Page 25: 09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)](https://reader034.vdocuments.us/reader034/viewer/2022050904/5480bd715906b5d76c8b45af/html5/thumbnails/25.jpg)
![Page 26: 09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)](https://reader034.vdocuments.us/reader034/viewer/2022050904/5480bd715906b5d76c8b45af/html5/thumbnails/26.jpg)
Core Features of AngularJS Two Way Data-binding
Model View Whatever
HTML Templates
Deep Linking
Dependency Injection
Directives
![Page 27: 09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)](https://reader034.vdocuments.us/reader034/viewer/2022050904/5480bd715906b5d76c8b45af/html5/thumbnails/27.jpg)
Two Way Data-Binding
![Page 28: 09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)](https://reader034.vdocuments.us/reader034/viewer/2022050904/5480bd715906b5d76c8b45af/html5/thumbnails/28.jpg)
Two Way Data-Binding<span id="yourName"></span>document.getElementById('yourName')[0].text = 'bob';
<span>{{yourName}}</span> var yourName = 'bob';
![Page 29: 09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)](https://reader034.vdocuments.us/reader034/viewer/2022050904/5480bd715906b5d76c8b45af/html5/thumbnails/29.jpg)
Model View Whatever
![Page 30: 09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)](https://reader034.vdocuments.us/reader034/viewer/2022050904/5480bd715906b5d76c8b45af/html5/thumbnails/30.jpg)
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"} ];}
![Page 31: 09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)](https://reader034.vdocuments.us/reader034/viewer/2022050904/5480bd715906b5d76c8b45af/html5/thumbnails/31.jpg)
Deep Linking
![Page 32: 09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)](https://reader034.vdocuments.us/reader034/viewer/2022050904/5480bd715906b5d76c8b45af/html5/thumbnails/32.jpg)
Dependency Injectionfunction EditCtrl($scope, $location, $routeParams, User) { // Something clever here...}
![Page 33: 09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)](https://reader034.vdocuments.us/reader034/viewer/2022050904/5480bd715906b5d76c8b45af/html5/thumbnails/33.jpg)
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>
![Page 34: 09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)](https://reader034.vdocuments.us/reader034/viewer/2022050904/5480bd715906b5d76c8b45af/html5/thumbnails/34.jpg)
Other featuresFilters
<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;
});
![Page 35: 09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)](https://reader034.vdocuments.us/reader034/viewer/2022050904/5480bd715906b5d76c8b45af/html5/thumbnails/35.jpg)
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>
![Page 36: 09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)](https://reader034.vdocuments.us/reader034/viewer/2022050904/5480bd715906b5d76c8b45af/html5/thumbnails/36.jpg)
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
![Page 37: 09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)](https://reader034.vdocuments.us/reader034/viewer/2022050904/5480bd715906b5d76c8b45af/html5/thumbnails/37.jpg)
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 amigoamigo todo
![Page 38: 09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)](https://reader034.vdocuments.us/reader034/viewer/2022050904/5480bd715906b5d76c8b45af/html5/thumbnails/38.jpg)
Amigo features
Resources scaffolding
MongoDB storage
Angular Routes
Angular Resources Factories
CRUD UI out of the box
Authentification
Session support and storing
![Page 39: 09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)](https://reader034.vdocuments.us/reader034/viewer/2022050904/5480bd715906b5d76c8b45af/html5/thumbnails/39.jpg)
Demo
![Page 40: 09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)](https://reader034.vdocuments.us/reader034/viewer/2022050904/5480bd715906b5d76c8b45af/html5/thumbnails/40.jpg)
Thanks
http://becevka.github.io/amigo/