Building Applications With the MEAN Stack
Transcript of 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
About meNir Noy
Full stack DeveloperWeb ConsultantSpeaker
Co-Organizer Of FrontEnd.IL Meetup Group
http://www.meetup.com/FrontEnd-IL
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
What is MEAN?
The MEAN StackThe 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.jsA JavaScript runtime that is designed for asynchronous IO operationsVery lightweight and fastBeing used by a growing number of companies:
The Node.js ecosystemNode.js has a rapidly growing ecosystem:
Web frameworks:ExpressSocket.io
Database supportSql DatabasesNoSql Databases
Hosting and Cloud environmentsIIS, AzureHerokuJoyent
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
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
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 .
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.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.
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.
Demo
Async server in Node.js
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.
Node.js Event loop
Server
Register Callback
AsyncWorkers
DDB, FS, Network,
etc…
Request
Response
Request
ResponseRegister Callback
Demo
Node.js single thread
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.
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.
Node Package Manager (NPM)The Node Package Manager (NPM) provides a management mechanism for modules:
Download and installVersion managementDeployment
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
{ "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 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.
ExpressJS
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
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.
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 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
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 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
Demo
Express
MongoDB
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
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
Demo
Express With Mongo
Angular 2
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
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
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 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
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 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)
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
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
Angular2 ArchitectureData is Flowing downwards.
Root Component
Child Compoment-A
grandChild Compoment-A1
grandChild Compoment-A2
Child Compoment-B
grandChild Compoment-B
Data Binding
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
Angular2 ArchitectureEach Component Can consume injectable Services.
Component
Service A
Service B
Service C
Dependency
injection
Dependency injection
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
Demo
Hello Angular 2
Scaffolding
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.
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)
Thank YouNir Noy | @noynir | [email protected]