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