© Copyright SELA software & Education Labs Ltd. | 14-18 Baruch Hirsch St Bnei Brak, 51202 Israel | www.selagroup.com
Nir Noy
Building Applications
With the MEAN stack
About me
Nir Noy
Full stack Developer
Web Consultant
Speaker
Co-Organizer Of FrontEnd.IL Meetup Group
http://www.meetup.com/FrontEnd-IL
Upcoming Meetup
FrontEnd.IL Meetup – Advanced Angular 2
https://www.meetup.com/FrontEnd-IL/events/233531658/
27/9/2016 – The Passage Bar, Tel Aviv
Angular 2 With Redux
Change Detection in Angular 2
What is MEAN?
The MEAN Stack
The term MEAN stack refers to a collection of
JavaScript based technologies used to develop
web applications.
M E A N
Node.js
What is Node.js
A JavaScript runtime that is designed for
asynchronous IO operations
Very lightweight and fast
Being used by a growing number of companies:
The Node.js ecosystem
Node.js has a rapidly growing ecosystem:
Web frameworks:
Express
Socket.io
Database support
Sql Databases
NoSql Databases
Hosting and Cloud environments
IIS, Azure
Heroku
Joyent
Synchronous server operations
// GET api/countries
public string Get()
{
var client = WebRequest.Create("http://.../");
var response = client.GetResponse();
var stream = response.GetResponseStream();
var reader = new StreamReader(stream);
return reader.ReadToEnd();
}
Blocking I/O operation
The Cost of I/O
I/O Operations are expensive.
I/O Source CPU Cycles
L1 – Cache 3
L2 – Cache 14
RAM 250
Disk 41,000,000
Network 240,000,000
Handling I/O
Waiting for I/O operations to complete is one of
the most common performance bottlenecks.
There are several common solutions to handle
it:
Synchronous
Pros: simple.
Cons: blocking, can hold up other requests.
Fork a new process
Pros: efficient, not holding up other requests.
Cons: does not scale, ~100 connections=~100 processes .
Handling I/O
Threads:
Pros:
efficient, not holding up other requests but more
lightweight then executing another process
Cons:
memory-expensive - ~1MB per thread, complicated, need
to worry about controlling access and shared resources.
Traditional web-servers (IIS, Apache) today use
an optimized thread-per-connection model that
uses thread pools.
Handling I/O in Node.js
Node.js runs your code on a single thread.
All I/O operations are asynchronous and Non-
Blocking
Internally threads and processes are used but not
explicitly exposed to your code.
When an I/O operation completes, an event is
triggered and the result is passed to a callback
function.
Why Node.js
Lightweight and efficient
using non-blocking I/O keeps memory consumption
stable by reducing the number of threads.
Less context switching overhead.
Concurrency
using non-blocking I/O keeps the main thread
responsive and allowing it support tens of thousands
of concurrent connections.
One Language
allows reuse of resources between the client and
server.
Demo
Async server in Node.js
Node.js Event loop
I/O operations are evented and external events
are handled by Node’s Event loop.
Javascript functions are passed to a queue and
invoked when the return value from their
current I/O calls is available.
I/O Callbacks are invoked synchronously by the
order they returned.
Node.js Event loop
Server
Async
Workers
DDB, FS,
Network,
etc…
Request
Response
Request
Response
Demo
Node.js single thread
Node.js Usage
Running CPU intensive tasks (e.g. long running
loops) on Node.js’s main thread should be
avoided as it will block handling other requests
to the server.
Running CPU intensive tasks can be scaled out
to multiple node processes.
Node.js can run a managed cluster of multiple
processes to scale out an entire application.
Node.js process architecture
Node.exe
V8
CommonJS – Module loader
JavaScript Application
libuv
OS
Core Javascript modules for file
system, network, http, etc…
Responsible for loading modules
and manage dependencies.
Using CommonJS’s module
definition.
Multi-platform library written in C
that handles all async I/O
operations.
Google’s Javascript Engine.
Compiles the Javascript code to
native machine code.
Node Package Manager (NPM)
The Node Package Manager (NPM) provides a
management mechanism for modules:
Download and install
Version management
Deployment
Managing Dependencies
NPM packages are managed in a file called
package.json
package.json schema define fields like:
name, description
Version
Dependencies
Dependencies are being resolved during NPM
install
{
"name": "app",
"version": "0.0.0",
"private": true,
"scripts": {
"start": "node ./bin/www"
},
"dependencies": {
"body-parser": "~1.10.2",
"cookie-parser": "~1.3.3",
"debug": "~2.1.1",
"express": "~4.11.1",
"jade": "~1.9.1",
"lodash": "^3.3.1",
"morgan": "~1.5.1",
"serve-favicon": "~2.2.0"
}
}
A look at Package.json
Managing Dependencies
NPM packages are installed inside a folder
named node_modules
The folder is created inside the path where the
“npm install …” was executed.
When a npm module is required node will look
it up inside the node_modules folder of the
current path.
If the module is not found it is recursively searched
up the folder tree.
ExpressJS
Introduction to ExpressJS
Node.js http module provides bare-bones HTTP
server functionality
Building a modern web application server
would require implementing many common
features such as:
Routing
Session Management
Cookies & Requests Parsers
Request Logging
Introduction to ExpressJS
ExpressJS is a web application framework
inspired by Sinatra.
Express middleware provides an expendable
Http pipeline on top of Node.js's httpServer
An Express application is essentially a series of
middleware calls
A middleware is simply a function with access to
the request object, response object and a
callback to next middleware in line.
ExpressJS is available through npm
$ npm install express --save
ExpressJS provides a generator tool to quickly
create an application skeleton.
$ npm install express-generator –g
//run
$ express -h
ExpressJS Installation
Routing is one of the pillars of ExpressJS
To create a route use the app.verb convention
// respond with "Hello World!" on the homepage
app.get('/', function (req, res) {
res.send('Hello World!');
})
// accept POST request on the homepage
app.post('/', function (req, res) {
res.send('Got a POST request');
})
// accept PUT request at /user
app.put('/user', function (req, res) {
res.send('Got a PUT request at /user');
})
Routing
A router is an isolated instance of middlewares
and routes.
The router can have middleware and http VERB
routes added just like an application.
var router = express.Router([options]);
router.get('/events', function(req, res, next) {
// .. some logic here .. like any other middleware // ..
});
Routers
Routing and Parameters
Express support parameters as part of the URI
Declare a parameter in the URI by using a “:” in front
of it
Access query-string parameters using req.query
Use regular expressions
Demo
Express
MongoDB
MongoDB
MongoDB is a document database
Stores BSON (Binary JSON) documents
Can search based on data stored in the BSON
document
Easily return results in JSON
MongoDB is one of the Most popular databases
in the Node.js eco-system
ODM with Mongoose
Object Data Model (ODM) tools allow you to
create an object model in your applications that
map to documents
Mongoose allows you to create schemas for
objects and bind them to MongoDB documents
Demo
Express With Mongo
Angular 2
Angular 2 Overview
Angular 2 is a new framework for building
javascript applications.
Open source (MIT license), written by Google
Fast and small
Modern approach, tools and practices
Designed for modern architectures and
challenges
Setting up an Angular 2 Project
Angular 2 projects almost always use a build
Have many dependencies
Require a lot of configuration
There are several approaches to setting up
Angular 2 projects:
Manually
Using a Yeoman generator
Using the Angular 2 CLI
Using an Angular 2 seed project
https://github.com/angular/angular2-seed
Angular 2 Development
Environment
SystemJS / Webpack
• Javascript module bundler
Typescript + ES 2015
• A Javascript Superset
• Official Language of Angular 2
npm
• Node.js package manager.
Node.js
• Server Javascript runtime.
• Used For Webservers and scripting
tools
The Build Process
Written code and executed code are different
Any build system can be used (webpack,
SystemJS, gulp, etc.)
Develop
•Write code
using
TypeScript,
Less, etc.
Build
•Transpile
•Lint
•Test
•Prerender
Execute
• JavaScript in
the browser
• Natively on
other target
platforms
Basic Angular Project Structure
/package.json  the Node project file
/tsconfig.json  the TypeScript project file
/typings.json  the Typings manifest file
/node_modules  the Node modules folder
/typings  the Typings folder
/src  the source code folder
From MVC to Components
Components are a higher-
level abstraction than MVC
MV* Frameworks focuses on
controllers
Angular 2 focuses on
components
Component classes implement
logic
Controllers and views are
metadata
Components
(Angular 2)
Views and Controllers
(MV* frameworks)
Angular2 Architecture
An Angular2 application is a tree of
components.
Root
Component
Child
Compoment-A
grandChild
Compoment-A1
grandChild
Compoment-A2
Child
Compoment-B
grandChild
Compoment-B
Angular2 Architecture
Components Communicate in a unidirectional
data flow
Root
Component
Child
Compoment-A
grandChild
Compoment-A1
grandChild
Compoment-A2
Child
Compoment-B
grandChild
Compoment-B
Angular2 Architecture
Data is Flowing downwards.
Root
Component
Child
Compoment-A
grandChild
Compoment-A1
grandChild
Compoment-A2
Child
Compoment-B
grandChild
Compoment-B
DataBinding
Angular2 Architecture
Events are Flowing upwards.
Root
Component
Child
Compoment-A
grandChild
Compoment-A1
grandChild
Compoment-A2
Child
Compoment-B
grandChild
Compoment-B
DataBinding
EventBinding
Angular2 Architecture
Each Component Can consume injectable
Services.
Component
Service A
Service B
Service C
Angular2 Architecture
Components, Services, Directives and Pipes are
all defined inside Angular Modules
Module A
Component A Pipe A Service A Directive A
Module B
Component
B
Service BImports
Demo
Hello Angular 2
Scaffolding
Yeoman
Yeoman is Node.js based tool, that helps
kickstart new projects.
With a set of plugins called “generators” you
can scaffold complete projects or useful parts.
“Generators” promote a robust and opinionated
tehcnology stack based on common standards
and best practices.
Yeoman MEAN Generators
There Several Common MEAN generators:
angular-fullstack – Most updated MEAN generator
with angular 1.x
Meanjs – Generator by of the creators of MEAN
https://github.com/datatypevoid/vulgar - generator
with Angular 2 (updated to Angular 2 RC1)
Thank You
Nir Noy | @noynir | nirn@sela.co.il

Building Applications With the MEAN Stack

  • 1.
    © Copyright SELAsoftware & Education Labs Ltd. | 14-18 Baruch Hirsch St Bnei Brak, 51202 Israel | www.selagroup.com Nir Noy Building Applications With the MEAN stack
  • 2.
    About me Nir Noy Fullstack Developer Web Consultant Speaker Co-Organizer Of FrontEnd.IL Meetup Group http://www.meetup.com/FrontEnd-IL
  • 3.
    Upcoming Meetup FrontEnd.IL Meetup– Advanced Angular 2 https://www.meetup.com/FrontEnd-IL/events/233531658/ 27/9/2016 – The Passage Bar, Tel Aviv Angular 2 With Redux Change Detection in Angular 2
  • 4.
  • 5.
    The MEAN Stack Theterm MEAN stack refers to a collection of JavaScript based technologies used to develop web applications.
  • 6.
  • 7.
  • 8.
    What is Node.js AJavaScript runtime that is designed for asynchronous IO operations Very lightweight and fast Being used by a growing number of companies:
  • 9.
    The Node.js ecosystem Node.jshas a rapidly growing ecosystem: Web frameworks: Express Socket.io Database support Sql Databases NoSql Databases Hosting and Cloud environments IIS, Azure Heroku Joyent
  • 10.
    Synchronous server operations //GET api/countries public string Get() { var client = WebRequest.Create("http://.../"); var response = client.GetResponse(); var stream = response.GetResponseStream(); var reader = new StreamReader(stream); return reader.ReadToEnd(); } Blocking I/O operation
  • 11.
    The Cost ofI/O I/O Operations are expensive. I/O Source CPU Cycles L1 – Cache 3 L2 – Cache 14 RAM 250 Disk 41,000,000 Network 240,000,000
  • 12.
    Handling I/O Waiting forI/O operations to complete is one of the most common performance bottlenecks. There are several common solutions to handle it: Synchronous Pros: simple. Cons: blocking, can hold up other requests. Fork a new process Pros: efficient, not holding up other requests. Cons: does not scale, ~100 connections=~100 processes .
  • 13.
    Handling I/O Threads: Pros: efficient, notholding up other requests but more lightweight then executing another process Cons: memory-expensive - ~1MB per thread, complicated, need to worry about controlling access and shared resources. Traditional web-servers (IIS, Apache) today use an optimized thread-per-connection model that uses thread pools.
  • 14.
    Handling I/O inNode.js Node.js runs your code on a single thread. All I/O operations are asynchronous and Non- Blocking Internally threads and processes are used but not explicitly exposed to your code. When an I/O operation completes, an event is triggered and the result is passed to a callback function.
  • 15.
    Why Node.js Lightweight andefficient using non-blocking I/O keeps memory consumption stable by reducing the number of threads. Less context switching overhead. Concurrency using non-blocking I/O keeps the main thread responsive and allowing it support tens of thousands of concurrent connections. One Language allows reuse of resources between the client and server.
  • 16.
  • 17.
    Node.js Event loop I/Ooperations are evented and external events are handled by Node’s Event loop. Javascript functions are passed to a queue and invoked when the return value from their current I/O calls is available. I/O Callbacks are invoked synchronously by the order they returned.
  • 18.
    Node.js Event loop Server Async Workers DDB,FS, Network, etc… Request Response Request Response
  • 19.
  • 20.
    Node.js Usage Running CPUintensive tasks (e.g. long running loops) on Node.js’s main thread should be avoided as it will block handling other requests to the server. Running CPU intensive tasks can be scaled out to multiple node processes. Node.js can run a managed cluster of multiple processes to scale out an entire application.
  • 21.
    Node.js process architecture Node.exe V8 CommonJS– Module loader JavaScript Application libuv OS Core Javascript modules for file system, network, http, etc… Responsible for loading modules and manage dependencies. Using CommonJS’s module definition. Multi-platform library written in C that handles all async I/O operations. Google’s Javascript Engine. Compiles the Javascript code to native machine code.
  • 22.
    Node Package Manager(NPM) The Node Package Manager (NPM) provides a management mechanism for modules: Download and install Version management Deployment
  • 23.
    Managing Dependencies NPM packagesare managed in a file called package.json package.json schema define fields like: name, description Version Dependencies Dependencies are being resolved during NPM install
  • 24.
    { "name": "app", "version": "0.0.0", "private":true, "scripts": { "start": "node ./bin/www" }, "dependencies": { "body-parser": "~1.10.2", "cookie-parser": "~1.3.3", "debug": "~2.1.1", "express": "~4.11.1", "jade": "~1.9.1", "lodash": "^3.3.1", "morgan": "~1.5.1", "serve-favicon": "~2.2.0" } } A look at Package.json
  • 25.
    Managing Dependencies NPM packagesare installed inside a folder named node_modules The folder is created inside the path where the “npm install …” was executed. When a npm module is required node will look it up inside the node_modules folder of the current path. If the module is not found it is recursively searched up the folder tree.
  • 26.
  • 27.
    Introduction to ExpressJS Node.jshttp module provides bare-bones HTTP server functionality Building a modern web application server would require implementing many common features such as: Routing Session Management Cookies & Requests Parsers Request Logging
  • 28.
    Introduction to ExpressJS ExpressJSis a web application framework inspired by Sinatra. Express middleware provides an expendable Http pipeline on top of Node.js's httpServer An Express application is essentially a series of middleware calls A middleware is simply a function with access to the request object, response object and a callback to next middleware in line.
  • 29.
    ExpressJS is availablethrough npm $ npm install express --save ExpressJS provides a generator tool to quickly create an application skeleton. $ npm install express-generator –g //run $ express -h ExpressJS Installation
  • 30.
    Routing is oneof the pillars of ExpressJS To create a route use the app.verb convention // respond with "Hello World!" on the homepage app.get('/', function (req, res) { res.send('Hello World!'); }) // accept POST request on the homepage app.post('/', function (req, res) { res.send('Got a POST request'); }) // accept PUT request at /user app.put('/user', function (req, res) { res.send('Got a PUT request at /user'); }) Routing
  • 31.
    A router isan isolated instance of middlewares and routes. The router can have middleware and http VERB routes added just like an application. var router = express.Router([options]); router.get('/events', function(req, res, next) { // .. some logic here .. like any other middleware // .. }); Routers
  • 32.
    Routing and Parameters Expresssupport parameters as part of the URI Declare a parameter in the URI by using a “:” in front of it Access query-string parameters using req.query Use regular expressions
  • 33.
  • 34.
  • 35.
    MongoDB MongoDB is adocument database Stores BSON (Binary JSON) documents Can search based on data stored in the BSON document Easily return results in JSON MongoDB is one of the Most popular databases in the Node.js eco-system
  • 36.
    ODM with Mongoose ObjectData Model (ODM) tools allow you to create an object model in your applications that map to documents Mongoose allows you to create schemas for objects and bind them to MongoDB documents
  • 37.
  • 38.
  • 39.
    Angular 2 Overview Angular2 is a new framework for building javascript applications. Open source (MIT license), written by Google Fast and small Modern approach, tools and practices Designed for modern architectures and challenges
  • 40.
    Setting up anAngular 2 Project Angular 2 projects almost always use a build Have many dependencies Require a lot of configuration There are several approaches to setting up Angular 2 projects: Manually Using a Yeoman generator Using the Angular 2 CLI Using an Angular 2 seed project https://github.com/angular/angular2-seed
  • 41.
    Angular 2 Development Environment SystemJS/ Webpack • Javascript module bundler Typescript + ES 2015 • A Javascript Superset • Official Language of Angular 2 npm • Node.js package manager. Node.js • Server Javascript runtime. • Used For Webservers and scripting tools
  • 42.
    The Build Process Writtencode and executed code are different Any build system can be used (webpack, SystemJS, gulp, etc.) Develop •Write code using TypeScript, Less, etc. Build •Transpile •Lint •Test •Prerender Execute • JavaScript in the browser • Natively on other target platforms
  • 43.
    Basic Angular ProjectStructure /package.json  the Node project file /tsconfig.json  the TypeScript project file /typings.json  the Typings manifest file /node_modules  the Node modules folder /typings  the Typings folder /src  the source code folder
  • 44.
    From MVC toComponents Components are a higher- level abstraction than MVC MV* Frameworks focuses on controllers Angular 2 focuses on components Component classes implement logic Controllers and views are metadata Components (Angular 2) Views and Controllers (MV* frameworks)
  • 45.
    Angular2 Architecture An Angular2application is a tree of components. Root Component Child Compoment-A grandChild Compoment-A1 grandChild Compoment-A2 Child Compoment-B grandChild Compoment-B
  • 46.
    Angular2 Architecture Components Communicatein a unidirectional data flow Root Component Child Compoment-A grandChild Compoment-A1 grandChild Compoment-A2 Child Compoment-B grandChild Compoment-B
  • 47.
    Angular2 Architecture Data isFlowing downwards. Root Component Child Compoment-A grandChild Compoment-A1 grandChild Compoment-A2 Child Compoment-B grandChild Compoment-B DataBinding
  • 48.
    Angular2 Architecture Events areFlowing upwards. Root Component Child Compoment-A grandChild Compoment-A1 grandChild Compoment-A2 Child Compoment-B grandChild Compoment-B DataBinding EventBinding
  • 49.
    Angular2 Architecture Each ComponentCan consume injectable Services. Component Service A Service B Service C
  • 50.
    Angular2 Architecture Components, Services,Directives and Pipes are all defined inside Angular Modules Module A Component A Pipe A Service A Directive A Module B Component B Service BImports
  • 51.
  • 52.
  • 53.
    Yeoman Yeoman is Node.jsbased tool, that helps kickstart new projects. With a set of plugins called “generators” you can scaffold complete projects or useful parts. “Generators” promote a robust and opinionated tehcnology stack based on common standards and best practices.
  • 54.
    Yeoman MEAN Generators ThereSeveral Common MEAN generators: angular-fullstack – Most updated MEAN generator with angular 1.x Meanjs – Generator by of the creators of MEAN https://github.com/datatypevoid/vulgar - generator with Angular 2 (updated to Angular 2 RC1)
  • 55.
    Thank You Nir Noy| @noynir | nirn@sela.co.il

Editor's Notes