+ All Categories
Home > Software > Building Applications With the MEAN Stack

Building Applications With the MEAN Stack

Date post: 13-Feb-2017
Category:
Upload: nir-noy
View: 92 times
Download: 1 times
Share this document with a friend
55
© 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
Transcript
Page 1: Building Applications With the MEAN Stack

© Copyright SELA software & Education Labs Ltd. | 14-18 Baruch Hirsch St Bnei Brak, 51202 Israel | www.selagroup.com

Nir NoyBuilding Applications With the MEAN stack

Page 2: Building Applications With the MEAN Stack

About meNir Noy

Full stack DeveloperWeb ConsultantSpeaker

Co-Organizer Of FrontEnd.IL Meetup Group

http://www.meetup.com/FrontEnd-IL

Page 3: Building Applications With the MEAN Stack

Upcoming MeetupFrontEnd.IL Meetup – Advanced Angular 2

https://www.meetup.com/FrontEnd-IL/events/233531658/

27/9/2016 – The Passage Bar, Tel AvivAngular 2 With ReduxChange Detection in Angular 2

Page 4: Building Applications With the MEAN Stack

What is MEAN?

Page 5: Building Applications With the MEAN Stack

The MEAN StackThe term MEAN stack refers to a collection of JavaScript based technologies used to develop web applications.

Page 6: Building Applications With the MEAN Stack

M E A N

Page 7: Building Applications With the MEAN Stack

Node.js

Page 8: Building Applications With the MEAN Stack

What is Node.jsA JavaScript runtime that is designed for asynchronous IO operationsVery lightweight and fastBeing used by a growing number of companies:

Page 9: Building Applications With the MEAN Stack

The Node.js ecosystemNode.js has a rapidly growing ecosystem:

Web frameworks:ExpressSocket.io

Database supportSql DatabasesNoSql Databases

Hosting and Cloud environmentsIIS, AzureHerokuJoyent

Page 10: Building Applications With the MEAN Stack

Synchronous server operations// GET api/countriespublic 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

Page 11: Building Applications With the MEAN Stack

The Cost of I/OI/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

Page 12: Building Applications With the MEAN Stack

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:

SynchronousPros: simple.Cons: blocking, can hold up other requests.

Fork a new processPros: efficient, not holding up other requests.Cons: does not scale, ~100 connections=~100 processes .

Page 13: Building Applications With the MEAN Stack

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.

Page 14: Building Applications With the MEAN Stack

Handling I/O in Node.jsNode.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.

Page 15: Building Applications With the MEAN Stack

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.

Concurrencyusing non-blocking I/O keeps the main thread responsive and allowing it support tens of thousands of concurrent connections.

One Languageallows reuse of resources between the client and server.

Page 16: Building Applications With the MEAN Stack

Demo

Async server in Node.js

Page 17: Building Applications With the MEAN Stack

Node.js Event loopI/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.

Page 18: Building Applications With the MEAN Stack

Node.js Event loop

Server

Register Callback

AsyncWorkers

DDB, FS, Network,

etc…

Request

Response

Request

ResponseRegister Callback

Page 19: Building Applications With the MEAN Stack

Demo

Node.js single thread

Page 20: Building Applications With the MEAN Stack

Node.js UsageRunning 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.

Page 21: Building Applications With the MEAN Stack

Node.js process architectureNode.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.

Page 22: Building Applications With the MEAN Stack

Node Package Manager (NPM)The Node Package Manager (NPM) provides a management mechanism for modules:

Download and installVersion managementDeployment

Page 23: Building Applications With the MEAN Stack

Managing DependenciesNPM packages are managed in a file called package.jsonpackage.json schema define fields like:

name, descriptionVersionDependencies

Dependencies are being resolved during NPM install

Page 24: Building Applications With the MEAN Stack

{ "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

Page 25: Building Applications With the MEAN Stack

Managing DependenciesNPM 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.

Page 26: Building Applications With the MEAN Stack

ExpressJS

Page 27: Building Applications With the MEAN Stack

Introduction to ExpressJSNode.js http module provides bare-bones HTTP server functionalityBuilding a modern web application server would require implementing many common features such as:

RoutingSession ManagementCookies & Requests ParsersRequest Logging

Page 28: Building Applications With the MEAN Stack

Introduction to ExpressJSExpressJS is a web application framework inspired by Sinatra.Express middleware provides an expendable Http pipeline on top of Node.js's httpServerAn Express application is essentially a series of middleware callsA middleware is simply a function with access to the request object, response object and a callback to next middleware in line.

Page 29: Building Applications With the MEAN Stack

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

Page 30: Building Applications With the MEAN Stack

Routing is one of the pillars of ExpressJSTo create a route use the app.verb convention

// respond with "Hello World!" on the homepageapp.get('/', function (req, res) { res.send('Hello World!');})

// accept POST request on the homepageapp.post('/', function (req, res) { res.send('Got a POST request');})

// accept PUT request at /userapp.put('/user', function (req, res) { res.send('Got a PUT request at /user');})

Routing

Page 31: Building Applications With the MEAN Stack

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

Page 32: Building Applications With the MEAN Stack

Routing and ParametersExpress support parameters as part of the URI

Declare a parameter in the URI by using a “:” in front of itAccess query-string parameters using req.query Use regular expressions

Page 33: Building Applications With the MEAN Stack

Demo

Express

Page 34: Building Applications With the MEAN Stack

MongoDB

Page 35: Building Applications With the MEAN Stack

MongoDBMongoDB is a document database

Stores BSON (Binary JSON) documentsCan 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

Page 36: Building Applications With the MEAN Stack

ODM with Mongoose Object Data Model (ODM) tools allow you to create an object model in your applications that map to documentsMongoose allows you to create schemas for objects and bind them to MongoDB documents

Page 37: Building Applications With the MEAN Stack

Demo

Express With Mongo

Page 38: Building Applications With the MEAN Stack

Angular 2

Page 39: Building Applications With the MEAN Stack

Angular 2 OverviewAngular 2 is a new framework for building javascript applications.

Open source (MIT license), written by Google

Fast and smallModern approach, tools and practicesDesigned for modern architectures and challenges

Page 40: Building Applications With the MEAN Stack

Setting up an Angular 2 Project

Angular 2 projects almost always use a buildHave many dependenciesRequire a lot of configuration

There are several approaches to setting up Angular 2 projects:

ManuallyUsing a Yeoman generatorUsing the Angular 2 CLIUsing an Angular 2 seed projecthttps://github.com/angular/angular2-seed

Page 41: Building Applications With the MEAN Stack

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

Page 42: Building Applications With the MEAN Stack

The Build ProcessWritten 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

Page 43: Building Applications With the MEAN Stack

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

Page 44: Building Applications With the MEAN Stack

From MVC to ComponentsComponents are a higher-level abstraction than MVC

MV* Frameworks focuses on controllers

Angular 2 focuses on components

Component classes implement logicControllers and views are metadata

Components(Angular 2)

Views and Controllers(MV* frameworks)

Page 45: Building Applications With the MEAN Stack

Angular2 ArchitectureAn Angular2 application is a tree of components.

Root Component

Child Compoment-A

grandChild Compoment-A1

grandChild Compoment-A2

Child Compoment-B

grandChild Compoment-B

Page 46: Building Applications With the MEAN Stack

Angular2 ArchitectureComponents Communicate in a unidirectional data flow

Root Component

Child Compoment-A

grandChild Compoment-A1

grandChild Compoment-A2

Child Compoment-B

grandChild Compoment-B

Page 47: Building Applications With the MEAN Stack

Angular2 ArchitectureData is Flowing downwards.

Root Component

Child Compoment-A

grandChild Compoment-A1

grandChild Compoment-A2

Child Compoment-B

grandChild Compoment-B

Data Binding

Page 48: Building Applications With the MEAN Stack

Angular2 ArchitectureEvents are Flowing upwards.

Root Component

Child Compoment-A

grandChild Compoment-A1

grandChild Compoment-A2

Child Compoment-B

grandChild Compoment-B

Data BindingEv

ent B

indi

ng

Page 49: Building Applications With the MEAN Stack

Angular2 ArchitectureEach Component Can consume injectable Services.

Component

Service A

Service B

Service C

Dependency

injection

Dependency injection

Page 50: Building Applications With the MEAN Stack

Angular2 ArchitectureComponents, 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

Page 51: Building Applications With the MEAN Stack

Demo

Hello Angular 2

Page 52: Building Applications With the MEAN Stack

Scaffolding

Page 53: Building Applications With the MEAN Stack

YeomanYeoman 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.

Page 54: Building Applications With the MEAN Stack

Yeoman MEAN GeneratorsThere Several Common MEAN generators:

angular-fullstack – Most updated MEAN generator with angular 1.xMeanjs – Generator by of the creators of MEANhttps://github.com/datatypevoid/vulgar - generator with Angular 2 (updated to Angular 2 RC1)

Page 55: Building Applications With the MEAN Stack

Thank YouNir Noy | @noynir | [email protected]


Recommended