Upload
others
View
2
Download
0
Embed Size (px)
Citation preview
Live! 360 Orlando 2015
VSM03 - Workshop: Busy Developer's Guide to MEANJS - Ted NewardCopyright (c) 2015 Neward & Associates. All rights reserved.This presentation is intended for informational use only.
Busy Developer's Workshopto MEANJS
Ted Neward
Neward & Associates
http://www.tedneward.com | [email protected]
Credentials
Who is this guy?– CTO, iTrellis (http://www.itrellis.com)
ask me how we can help your project, your team or your firm
– Microsoft MVP (F#, C#, Architect); JSR 175, 277 EG
– Author
Professional F# 2.0 (w/Erickson, et al; Wrox, 2010)Effective Enterprise Java (Addison‐Wesley, 2004)SSCLI Essentials (w/Stutz, et al; OReilly, 2003)Server‐Based Java Programming (Manning, 2000)
– Blog: http://blogs.tedneward.com
– Writing: http://www.newardassociates.com/writing.html
– Twitter: @tedneward
– For more, see http://www.newardassociates.com/about.html
Live! 360 Orlando 2015
VSM03 - Workshop: Busy Developer's Guide to MEANJS - Ted NewardCopyright (c) 2015 Neward & Associates. All rights reserved.This presentation is intended for informational use only.
Objectives
Before we are done, we wil...– ... examine a popular Web stack (MEAN)
– ... talk briefly about its components
– ... see how Javascript "wires up" together
– ... explore a given MEAN stack (MEANJS)
Beginnings
What is this thing MEAN?– MongoDB
– Express
– AngularJS
– NodeJS
Live! 360 Orlando 2015
VSM03 - Workshop: Busy Developer's Guide to MEANJS - Ted NewardCopyright (c) 2015 Neward & Associates. All rights reserved.This presentation is intended for informational use only.
Beginnings
What is this thing MEAN, really?– Any database except a SQL one
– NodeJS + Express (most of the time)
– Some SPA‐capable client‐side stack
– HTTP‐based ("WebAPI" or "RESTful") communications
– ... all while developers wear beards
Beginnings
What is this thing MEAN, really really?– Rejection of the heavyweight enterprise stacks
JavaEE, .NET WCF, etc
– Embracing the dynamic of Ruby...
lots of Ruby‐inspired ideas in here...
– ... without embracing Ruby (or its community)
because, you know, it's Ruby
– Oh, and it's "JavaScript Everywhere"
because, you know, it's JavaScript!
Live! 360 Orlando 2015
VSM03 - Workshop: Busy Developer's Guide to MEANJS - Ted NewardCopyright (c) 2015 Neward & Associates. All rights reserved.This presentation is intended for informational use only.
Beginnings
Reality check– There is nothing you can build in MEAN that cannot be built in another language/platform
– Success with MEAN will depend as much on your developers' skill than the platform (as usual)
– Node's "event‐driven" I/O is not new or unique
it will not solve all your concurrency problems for you!
Beginnings
Assumptions: I am assuming...– ... that you know some JavaScript
– ... that you haven't spent much time w/NodeJS
– ... that you're aware of MongoDB and/or other NoSQLs
– ... that you know what a Single‐Page Application is
– ... that you're not here to "defend" your favorite stack
life's too short, really
Live! 360 Orlando 2015
VSM03 - Workshop: Busy Developer's Guide to MEANJS - Ted NewardCopyright (c) 2015 Neward & Associates. All rights reserved.This presentation is intended for informational use only.
JavaScript
Best to go over this, first
ECMAScript Overview
Live! 360 Orlando 2015
VSM03 - Workshop: Busy Developer's Guide to MEANJS - Ted NewardCopyright (c) 2015 Neward & Associates. All rights reserved.This presentation is intended for informational use only.
Overview
ECMAScript has ...– ... an imperative C‐family‐of‐languages syntax
– ... a classless object system
– ... functional objects
– ... loosely‐typed type system
– ... a metaobject protocol
– ... a garbage collected object heap
– ... and a few bad design decisions/legacy
ECMAScript Basics
Live! 360 Orlando 2015
VSM03 - Workshop: Busy Developer's Guide to MEANJS - Ted NewardCopyright (c) 2015 Neward & Associates. All rights reserved.This presentation is intended for informational use only.
Basics
Starting points– Whitespace: space, tabs, CRLF, etc
mostly irrelevantline terminator (";") mostly optional
– Comments: // (end‐of‐line) and /* */ (multi‐line)
– Identifiers/Names: [A‐Za‐z][A‐Za‐z0‐9...]
– Numbers: always a 64‐bit floating‐point type, NaN
– Strings: 16‐bit Unicode
Variables
Variables– signified with "var" keyword, followed by legal name
– any variable used without "var" declaration is global
this is generally considered badbe particularly careful in "for" loops
– variables are typeless
but the things they point to are typedjust not very strongly; coercion is always possible
Live! 360 Orlando 2015
VSM03 - Workshop: Busy Developer's Guide to MEANJS - Ted NewardCopyright (c) 2015 Neward & Associates. All rights reserved.This presentation is intended for informational use only.
Flow control
Flow control primitives familiar to C‐family langs– if/else, switch/case, try/catch, while, do/while, for
"for (a in b)" is an iterating for
– test expressions are evaluated for "truthiness"
•'falsy' values: false, null, undefined, '', 0, NaN•'truthy' values: anything else
– labels are similar to C‐family syntax
•name: at the start of any line in a block•break is a labeled break•break; (exits current scope) or break label; (break to label)
– return always yields a value (undefined if nothing else)
– throw starts popping execution records looking for catch
Operators
Operators– operator set similar to that from C‐family langs
but there are some subtle and dangerous differences!
– + ‐ * / % : mathematical operators
– <= >= != < > : comparison operators
– === !== : equality/inequality operators
ES also supports == and !=, but they attempt conversion
– && || ! : logical operators
– typeof : returns type of object
object, function, undefined, Number, String, ...
Live! 360 Orlando 2015
VSM03 - Workshop: Busy Developer's Guide to MEANJS - Ted NewardCopyright (c) 2015 Neward & Associates. All rights reserved.This presentation is intended for informational use only.
Operators
What's truthy? What's falsy?
0 == '''' == '0'false == '0'false == nullnull == undefinedfalse == undefined
Operators
What's truthy? What's falsy?
0 == '' (true)'' == '0' (false)false == '0' (true)false == null (false)null == undefined (true)false == undefined (false)
Live! 360 Orlando 2015
VSM03 - Workshop: Busy Developer's Guide to MEANJS - Ted NewardCopyright (c) 2015 Neward & Associates. All rights reserved.This presentation is intended for informational use only.
Operators
Operators– . [] () : "refinement" and "invocation" operators
– any use of "." or "[]" is an attempt to refine (find a property)
– any use of "()" is an attempt to invoke
this is extremely powerful; we'll see this again later
Functions
Functions are first‐class citizens in ES– functions are objects, too
– composition: 4 parts
"function"name (optional)parameter set (0 ‐ n named arguments)statement block
– function can appear anywhere an expression is expected
top‐level, as object members, nested, and so on
– two implicit arguments to every function invocation
'this': reference whose contents vary with invocation pattern'arguments': array of arguments passed in
– unlike other languages, functions don't enforce arity
missing arguments are undefined, extras are in 'arguments'
Live! 360 Orlando 2015
VSM03 - Workshop: Busy Developer's Guide to MEANJS - Ted NewardCopyright (c) 2015 Neward & Associates. All rights reserved.This presentation is intended for informational use only.
Functions
Functions
function addIt(first, second) {return first + second
}println(addIt(1, 2))
var addItAgain = function(first, second) {return first + second
}println(addItAgain(1,2))
println(function(first, second) {return first + second
}(1, 2))
var add = function() {var result = 0;for (var i = 0; i<arguments.length; i++)
result += arguments[i]return result
}println(add(1, 2, 3, 4, 5))
Functions
Function invocation patterns– Function Invocation: function is not an object member
"this" is bound to the global object
– Method Invocation: function is an object member
"this" is bound to object on which function is being invoked
– Apply Invocation: function is invoked explicitly via apply()
"this" is bound to first argument in parameters list
– Constructor Invocation: function is used as a constructor
new object created with hidden link to function's prototype"this" is bound to newly‐created object(this style is discouraged; embrace prototypical construction)
Live! 360 Orlando 2015
VSM03 - Workshop: Busy Developer's Guide to MEANJS - Ted NewardCopyright (c) 2015 Neward & Associates. All rights reserved.This presentation is intended for informational use only.
Functions
Function scope– ES is not block‐scoped, as C‐family languages are
suggestion: declare vars before use at top of functionsuggestion: prefer functions, not blocks
– nested functions get access to outer function scope
known as "closure": variables referenced in nested function survive as long as inner function does
Functions
Function scope
function badScope() {for (var i = 0; i < 10; i++) {
for (var j = 0; j < 10; j++) {var i = i * jprintln(i)
}}
}//badScope() // never terminates!
function goodScope() {for (var i = 0; i < 10; i++) {
(function () {for (var j = 0; j < 10; j++) {
(function(i, j) {var i = i * jprintln(i)
})(i, j);}
})();}
}goodScope();
Live! 360 Orlando 2015
VSM03 - Workshop: Busy Developer's Guide to MEANJS - Ted NewardCopyright (c) 2015 Neward & Associates. All rights reserved.This presentation is intended for informational use only.
ECMAScript Objects
Objects
Objects are essentially a bag of name‐value pairs– values can be either data or function values
– classless system: no concept of "class", just "objects"
– "open" objects: members can be added/removed
– members accessed through refinement operators (. [])
– use [] to access illegal identifier names (as keys)
Live! 360 Orlando 2015
VSM03 - Workshop: Busy Developer's Guide to MEANJS - Ted NewardCopyright (c) 2015 Neward & Associates. All rights reserved.This presentation is intended for informational use only.
Objects
Objects
var speaker = {'firstName' : 'Ted','lastName' : 'Neward',sayHello : function() {
println("Hello!")},sayHowdy : function() {
println("Howdy!")}
}println(speaker.firstName)println(speaker["lastName"])speaker.sayHowdy()speaker["sayHello"]()
for (var m in speaker) {println(m + "=" + speaker[m])
}
Objects
Object prototypes– objects always have a "prototype" object
– prototype is always in scope when resolving names
– this creates a "prototype chain" of names
– we can control the prototype used at construction ...
... but the syntax for doing so in ECMAScript is... complicated.
– instead, monkey‐patch Object and add a create() method
Live! 360 Orlando 2015
VSM03 - Workshop: Busy Developer's Guide to MEANJS - Ted NewardCopyright (c) 2015 Neward & Associates. All rights reserved.This presentation is intended for informational use only.
Objects
Objects and prototypes
var empty = { }for (var m in empty) {
println(m + "=" + empty[m])}println(empty.toString())
Objects
Monkey‐patched Object.create:– this version explicitly creates empty object, then links it to the prototype object passed in
– doesn't change Object.prototype, however, localizing the change (which is also important)
Live! 360 Orlando 2015
VSM03 - Workshop: Busy Developer's Guide to MEANJS - Ted NewardCopyright (c) 2015 Neward & Associates. All rights reserved.This presentation is intended for informational use only.
Objects
Monkey-patching
if (typeof Object.create !== 'function') {Object.create = function(proto) {
var F = function() {};F.prototype = proto;return new F();
};}
var base = {sayHowdy : function() { println("Howdy") }
}var derived = Object.create(base)for (var m in derived) {
println(m + "=" + derived[m])}derived.sayHowdy()
Objects
This kind of "open object" system is extremely powerful programming– very Lisp‐ish/CLOS‐ish in nature
– sometimes also known as Meta‐Object Protocol (MOP)
– often used as building block for more powerful coding
Live! 360 Orlando 2015
VSM03 - Workshop: Busy Developer's Guide to MEANJS - Ted NewardCopyright (c) 2015 Neward & Associates. All rights reserved.This presentation is intended for informational use only.
Objects
Monkey-patching
// Method to add a method to any particular prototypeFunction.prototype.method = function (name, func) {
if (!this.prototype[name]) {this.prototype[name] = func;
}return this;
};// add an 'roundOff' method to NumberNumber.method('roundOff', function() {
return Math[this < 0 ? 'ceil' : 'floor'](this);});println((5.2).roundOff())println((‐12.2).roundOff())
Objects
Adding event-processing to any object
var eventuality = function(that) {var registry = {};that.fire = function(event) {
var array, func, handler, i;var type = typeof event === 'string' ?
event : event.type;if (registry.hasOwnProperty(type)) {
array = registry[type];for (i = 0; i < array.length; i++) {
handler = array[i];func = handler.method;if (typeof func === 'string') {
func = this[func];}func.apply(this, handler.parameters || [event]);
}}return this;
};
Live! 360 Orlando 2015
VSM03 - Workshop: Busy Developer's Guide to MEANJS - Ted NewardCopyright (c) 2015 Neward & Associates. All rights reserved.This presentation is intended for informational use only.
Objects
Adding event-processing to any object
that.on = function(type, method, parameters) {var handler = {
method : method,parameters : parameters
};if (registry.hasOwnProperty(type)) {
registry[type].push(handler);} else {
registry[type] = [handler];}return this;
};return that;
};
Objects
Adding event-processing to any object
var stooge = {"first‐name" : "Jerome","last‐name" : "Howard"
};var eventedStooge = eventuality(Object.create(stooge));
eventedStooge.on('poke', function() {println("Oh, a wiseguy, eh?");
});
eventedStooge.fire("poke");
Live! 360 Orlando 2015
VSM03 - Workshop: Busy Developer's Guide to MEANJS - Ted NewardCopyright (c) 2015 Neward & Associates. All rights reserved.This presentation is intended for informational use only.
Closure
Closure– referenced values remain around as long as function does
the function "closes over" the reference variable (hence the name)
– the actual link isn't explicit or discoverable
this provides opportunities to "hide" members from the object on which a function operates, to avoid pollution
Advanced ECMAScript
Brace yourselves....
Live! 360 Orlando 2015
VSM03 - Workshop: Busy Developer's Guide to MEANJS - Ted NewardCopyright (c) 2015 Neward & Associates. All rights reserved.This presentation is intended for informational use only.
Advanced
Modules: Use closures to encapsulate state and hide details
String.method('deentityify', function() {var entity = { quot : '"', lt : '<', gt: '>' };return function () {
return this.replace( /&([^&;]+)/g,function(a, b) {
var r = entity[b];return typeof r === 'string' ? r : a;
});};
} ());// last line invokes the function, which returns a// function, which is then the parameter to 'method'// and gets added to the String prototype// the entity array is only built once across all invocations//
var s = "<html>"print(s.deentityify())
Advanced
Currying: create new functions out of old by partially-applying the parameters required
function add (lhs, rhs) {return lhs + rhs;
}Function.method('curry', function() {
var slice = Array.prototype.slice,args = slice.apply(arguments),that = this;
return function () {return that.apply(null,
args.concat(slice.apply(arguments)));};
});var add1 = add.curry(1);var results = add1(6); // produces 7
Live! 360 Orlando 2015
VSM03 - Workshop: Busy Developer's Guide to MEANJS - Ted NewardCopyright (c) 2015 Neward & Associates. All rights reserved.This presentation is intended for informational use only.
Advanced
Memoization: remember the results of previous computations, to avoid rework
var fibonacci = function(n) {return n < 2 ? n : fibonacci(n‐1) + fibonacci(n‐2);
}for (var i = 0; i <= 10; i ++) {
println("Fibo " + i + ": " + fibonacci(i));}// computes fibonacci(3) a LOT of times
Advanced
Memoization: remember the results of previous computations, to avoid rework
var fibonacci = function() {var memo = [0, 1];var fib = function(n) {
var result = memo[n];if (typeof result !== 'number') {
result = fib(n ‐ 1) + fib(n ‐ 2);memo[n] = result;
}return result;
};return fib;
}();for (var i = 0; i <= 10; i ++) {
println("Fibo " + i + ": " + fibonacci(i));}// computes fibonacci(3) exactly once
Live! 360 Orlando 2015
VSM03 - Workshop: Busy Developer's Guide to MEANJS - Ted NewardCopyright (c) 2015 Neward & Associates. All rights reserved.This presentation is intended for informational use only.
Advanced
Memoization: generalization for all objects
var memoizer = function(memo, fundamental) {var shell = function(n) {
var result = memo[n];if (typeof result !== 'number') {
result = fundamental(shell, n);memo[n] = result;
}return result;
};return shell;
};
fibonacci = memoizer([0,1], function(shell, n) {return shell(n ‐ 1) + shell(n ‐ 2);
});factorial = memoizer([1, 1], function(shell, n) {
return n * shell(n ‐ 1);});
NodeJS
The N in MEAN
Live! 360 Orlando 2015
VSM03 - Workshop: Busy Developer's Guide to MEANJS - Ted NewardCopyright (c) 2015 Neward & Associates. All rights reserved.This presentation is intended for informational use only.
Starters
NodeJS is JavaScript... on the server– Yes, that's really all it is
– Actually, it's Javascript outside of the browser
•on the command‐line•in the NoSQL database•in your web server•on the server itself (outside of the web server)•anywhere else you can embed the V8 engine
Starters
So... why does everyone care?– Because JavaScript is hot
– (Seriously, that's pretty much it)
Live! 360 Orlando 2015
VSM03 - Workshop: Busy Developer's Guide to MEANJS - Ted NewardCopyright (c) 2015 Neward & Associates. All rights reserved.This presentation is intended for informational use only.
Starters
So... why does everyone care?– Because JavaScript is hot
– JavaScript‐on‐the‐client, JavaScript‐on‐the‐server
– Scripting language vs "system language" (Java, C#, etc)
– Lighter‐weight stack (Node vs JavaEE, Node vs .NET)
Truthfully, half the magic is in the packages (npm)
Starters
So... what does Node really look like?– Basically, just JavaScript without all the DOM stuff
– No "main()", just start executing from the top
Live! 360 Orlando 2015
VSM03 - Workshop: Busy Developer's Guide to MEANJS - Ted NewardCopyright (c) 2015 Neward & Associates. All rights reserved.This presentation is intended for informational use only.
Starters
Hello, Node
console.log("Hello, node!")
Running it
node helloNode
Getting Started
Installing Node– http://nodejs.org
•Windows: MSI install•MacOS X: DMG install
– Platform‐specific
•Windows: WebPI•MacOS X: brew install node
Live! 360 Orlando 2015
VSM03 - Workshop: Busy Developer's Guide to MEANJS - Ted NewardCopyright (c) 2015 Neward & Associates. All rights reserved.This presentation is intended for informational use only.
Getting Started
Verifying it's there
C:\> node ‐‐versionv0.10.26
$ node ‐‐versionv0.10.26
Getting Started
Hello, node
console.log("Hello, node!")
C:\> node helloNode.jsHello, node!
$ node helloNode.jsHello, node!
Live! 360 Orlando 2015
VSM03 - Workshop: Busy Developer's Guide to MEANJS - Ted NewardCopyright (c) 2015 Neward & Associates. All rights reserved.This presentation is intended for informational use only.
Starters
At heart, Node the Google V8 engine– tons of command‐line flags available
– most of them are irrelevant or trivial or esoteric
– get a list with "‐‐v8‐options" if you wish
Starters
Node runs as a REPL– help: Brings up help
– break: Abort current command mode (get back to prompt)
– clear: Clear REPL content
– exit: Out we go
Live! 360 Orlando 2015
VSM03 - Workshop: Busy Developer's Guide to MEANJS - Ted NewardCopyright (c) 2015 Neward & Associates. All rights reserved.This presentation is intended for informational use only.
NodeJS Modules
Understanding Node's module system
Modules
NodeJS uses modules to deconstruct monoliths– analogous to libraries, assemblies, or JARs
– modules help keep complexity down
•third‐party modules (usually obtained via npm)•your own modules (to keep files small/manageable)
Live! 360 Orlando 2015
VSM03 - Workshop: Busy Developer's Guide to MEANJS - Ted NewardCopyright (c) 2015 Neward & Associates. All rights reserved.This presentation is intended for informational use only.
Modules
More often than not, these are stored in node_modules– these are npm‐managed modules
– require() only needs the name (not a JS file)
Modules
Conventions– require() result is stored in a var
– var is usually the same name as the module
– this var is used as principal gateway into the module
in other words, it's usually an object
Live! 360 Orlando 2015
VSM03 - Workshop: Busy Developer's Guide to MEANJS - Ted NewardCopyright (c) 2015 Neward & Associates. All rights reserved.This presentation is intended for informational use only.
Modules
A simple application
var hello = require('./hello');var debug = require('debug')('app');
hello.world();
debug("You only see this if DEBUG is set to 'app'");
console.log("But you always see this");
require('./hello.js') fetches "hello.js"
require('debug') fetches the debug module
Modules
The dependent module
var debug = require('debug')('hello');
exports.world = function() {debug("This only shows up if DEBUG includes 'hello'");console.log('Hello World');
}
Live! 360 Orlando 2015
VSM03 - Workshop: Busy Developer's Guide to MEANJS - Ted NewardCopyright (c) 2015 Neward & Associates. All rights reserved.This presentation is intended for informational use only.
Modules
Modules can come with manifest files (package.json)– and these can in turn declare dependencies
– which npm will manage appropriately
– not necessary to know about unless you're building modules
which most NodeJS developers aren't, quite frankly
Modules
Note that all this will change with ES6– modules become a part of the language/platform
– import/export become actual keywords
– nevertheless, this convention will stick around for a while
too much of it to go away any time soon
Live! 360 Orlando 2015
VSM03 - Workshop: Busy Developer's Guide to MEANJS - Ted NewardCopyright (c) 2015 Neward & Associates. All rights reserved.This presentation is intended for informational use only.
NPM
Node Package Manager
npm
Node doesn't have everything "out of the box"– in fact, there is less in the box than expected
– fortunately, the box comes with a "grow the box" tool
Live! 360 Orlando 2015
VSM03 - Workshop: Busy Developer's Guide to MEANJS - Ted NewardCopyright (c) 2015 Neward & Associates. All rights reserved.This presentation is intended for informational use only.
npm
npm: Node Package Manager– command‐line tool to install/manage node packages
– full list of packages is at http://search.npmjs.org/
WARNING: this is a huge list, some are good, some are crapBetter to know what you want before hunting for it
– Must be online to use npm!
because it pulls package sources from npmjs.org, so...
npm
npm installs to a directory– node_modules/
– generally, treat this as opaque
•toying with this can open a huge Pandora's box•if it gets wedged, just nuke it and re‐install
– "global" installs will install to a user/system‐wide directory
varies with platform
Live! 360 Orlando 2015
VSM03 - Workshop: Busy Developer's Guide to MEANJS - Ted NewardCopyright (c) 2015 Neward & Associates. All rights reserved.This presentation is intended for informational use only.
npm
npm commands:– all take a "‐g" parameter to mean "global"
globally will require admin rights
– npm help {command}: man page on {command}
– often two forms:
•long name: "remove"•unix‐style alias: "rm"•either works
npm
npm init– creates npm manifest (package.json)
•describes dependencies•describes dev‐only dependencies•describes entry point script•describes other scripts•... and so on
– JSON format
Live! 360 Orlando 2015
VSM03 - Workshop: Busy Developer's Guide to MEANJS - Ted NewardCopyright (c) 2015 Neward & Associates. All rights reserved.This presentation is intended for informational use only.
package.json
package.json
{"name": "sample‐app","version": "1.0.0","description": "Sample application","main": "app.js","dependencies": {
"debug": "^2.2.0"},"devDependencies": {},"scripts": {
"test": "node ‐‐debug app.js"},"author": "Ted Neward","license": "ISC"
}
npm
npm install– npm install {package}
•downloads package to node_modules•if "‐‐save" or "‐‐save‐dev" is provided, saves to manifest
– npm install
•examines manifest•downloads all packages locally•typically used to set up code for execution
– there may be binaries/scripts installed
use "npm bin" to find out where
Live! 360 Orlando 2015
VSM03 - Workshop: Busy Developer's Guide to MEANJS - Ted NewardCopyright (c) 2015 Neward & Associates. All rights reserved.This presentation is intended for informational use only.
npm
npm ls / npm list / npm ll– list the packages installed
g will list all global packages installed
– ll will list in a "long" format
includes some additional info about the package
npm
npm upgrade / npm up– upgrade app dependencies to latest version
– subject to manifest's versioning declarations
•"^" dependencies will be upgraded to whatever's latest•"~" dependencies will only upgrade to latest minor version•so "^1.1.1" will upgrade to 1.1.2, 1.2.0, or 2.0•but "~1.1.1" will upgrade to 1.1.2, but not 1.2.0 or 2.0
– use "‐‐save" to record new versions in manifest
Live! 360 Orlando 2015
VSM03 - Workshop: Busy Developer's Guide to MEANJS - Ted NewardCopyright (c) 2015 Neward & Associates. All rights reserved.This presentation is intended for informational use only.
npm
npm remove / npm rm– removes the package from the application
– use "‐‐save" to record removal in the manifest
npm
npm {command}– "npm run" or "npm test" or ...
– directly corresponds to the "scripts" section in manifest
– commonly used as a lightweight build tool
•"npm test" to launch automated tests•"npm run" to kick off application execution
Live! 360 Orlando 2015
VSM03 - Workshop: Busy Developer's Guide to MEANJS - Ted NewardCopyright (c) 2015 Neward & Associates. All rights reserved.This presentation is intended for informational use only.
npm
npm explore {package}– open a shell in node_modules for {package}
– avoids having to resolve by hand
useful for package debugging
– not often used by non‐package developers
npm
Note: if npm fails– npm will display output to console window
– it will attempt to carry on
– it will write all output to "npm‐debug.log" in current directory
Live! 360 Orlando 2015
VSM03 - Workshop: Busy Developer's Guide to MEANJS - Ted NewardCopyright (c) 2015 Neward & Associates. All rights reserved.This presentation is intended for informational use only.
Modules
Some interesting modules to explore:– Socket.io: websockets server/client
– Connect: "middleware" framework
– Express: Web framework
– Geddy: Web framework
– Jade: templating engine
– TowerJS: Web framework++ (includes Connect and Express)
– More‐‐see https://github.com/joyent/node/wiki/modules
Exercise
Give it a spin
Live! 360 Orlando 2015
VSM03 - Workshop: Busy Developer's Guide to MEANJS - Ted NewardCopyright (c) 2015 Neward & Associates. All rights reserved.This presentation is intended for informational use only.
Exercise
Things to try right now:– "node hello.js": Hello World, for Node
– "npm install debug": Can you install an npm module?
– "node debugHello.js": Can you require() and use a module?
– "npm start": Can you modify the manifest to add a new command?
ExpressJS
The E in MEAN
Live! 360 Orlando 2015
VSM03 - Workshop: Busy Developer's Guide to MEANJS - Ted NewardCopyright (c) 2015 Neward & Associates. All rights reserved.This presentation is intended for informational use only.
ExpressJS
HTTP endpoints in NodeJS
ExpressJS
ExpressJS handles the networking for HTTP request/response processing– developers write "routing maps" that describe the endpoints and verbs
– developers wire up the routing maps to functions to process
– processing uses request and response parameters
•request object has access to incoming HTTP request data•response object accesses/creates HTTP response package
– Express also provides "middleware" functions for simplicity
Live! 360 Orlando 2015
VSM03 - Workshop: Busy Developer's Guide to MEANJS - Ted NewardCopyright (c) 2015 Neward & Associates. All rights reserved.This presentation is intended for informational use only.
ExpressJS
ExpressJS uses– server‐side HTML generation
traditional web app architecture
– "Web APIs"
minimal overhead means no unnecessary processing
Getting Started with ExpressJS
3... 2... 1... Go!
Live! 360 Orlando 2015
VSM03 - Workshop: Busy Developer's Guide to MEANJS - Ted NewardCopyright (c) 2015 Neward & Associates. All rights reserved.This presentation is intended for informational use only.
Getting Started
ExpressJS setup– for npm‐enabled projects, just install using npm
– make sure to save the dependency in the package.json
npm install express ‐‐save
– in traditional npm fashion, this pulls in all explicit dependencie
Getting Started
Writing your first ExpressJS app– if this is the VERY FIRST time, try the Express generator
npm install express‐generator ‐g
– npm with the ‐g parameter is "global install"
•this may require admin permissions, depending on your OS
– once installed, ask the generator to create an app skeleton
express ‐h (Show help and options)express myapp
– round out the scaffolding by installing dependencies
npm install
– and fire it up (with debugging output on, let's say)
OSX/Linux: DEBUG=mapp npm startWindows: set DEBUG=myapp & npm start
– browse
http://localhost:3000
Live! 360 Orlando 2015
VSM03 - Workshop: Busy Developer's Guide to MEANJS - Ted NewardCopyright (c) 2015 Neward & Associates. All rights reserved.This presentation is intended for informational use only.
Getting Started
Scaffolded application contains:– app.js: Entrypoint to the server application
actually it's bin/www, but all "real" work goes on in app.js
– package.json: npm dependencies
– routes/: Directory containing routing tables
•index.js: top‐level routing ("/")•users.js: routing for "/users" endpoints
– views/: JADE templates for HTML generation
– public/: static asset directory
ExpressJS Basics
What you absolutely need to know to know ExpressJS
Live! 360 Orlando 2015
VSM03 - Workshop: Busy Developer's Guide to MEANJS - Ted NewardCopyright (c) 2015 Neward & Associates. All rights reserved.This presentation is intended for informational use only.
ExpressJS
ExpressJS centers around "routing"– Express creates a Router object
•typically just one per app•this is where we register "routing map entries"
– Router can be obtained again later when desired
– this Router is often (by convention) labeled "app"
the "app" and "router" are often used synonymously
ExpressJS
Once the router is obtained, build the routing map– app.{verb}({URI‐pattern}, {function});
•verb is get(), post(), put(), delete(), and others•URI‐pattern is any legitimate relative URL•function is a Javascript function
Live! 360 Orlando 2015
VSM03 - Workshop: Busy Developer's Guide to MEANJS - Ted NewardCopyright (c) 2015 Neward & Associates. All rights reserved.This presentation is intended for informational use only.
ExpressJS
Once the routing map is built, start the app– call listen() on the port, passing in a callback invoked at startup
– typically this callback just spits info to the console and stops
– other one‐time initialization is possible, of course
ExpressJS
var express = require('express');var app = express();
app.get('/', function (req, res) {res.send('Hello World!');
});
var server = app.listen(3000, function () {var host = server.address().address;var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);});
Live! 360 Orlando 2015
VSM03 - Workshop: Busy Developer's Guide to MEANJS - Ted NewardCopyright (c) 2015 Neward & Associates. All rights reserved.This presentation is intended for informational use only.
ExpressJS
All routes are dynamic unless mapped as static– use express.static to specify a static asset directory
app.use(express.static('public'));
Exercise
Give it a spin
Live! 360 Orlando 2015
VSM03 - Workshop: Busy Developer's Guide to MEANJS - Ted NewardCopyright (c) 2015 Neward & Associates. All rights reserved.This presentation is intended for informational use only.
Exercise
Things to try right now:– "npm install express": Can you install Express?
– Can you write a GET / route that returns "hello world"?
– Can you write a POST /hello route that accepts a form?
"username", "password", and echo them back to the page
– Can you write CRUD routines for /persons?
•"id"/"firstName"/"lastName"/"status" for the JSON fields•use an in‐memory array of objects stored in the Express app•GET /persons: returns a JSON array of persons•POST /persons: accepts a new JSON object•PUT /persons/:id: modifies an existing person•DELETE /persons/:id: removes an existing person
MongoDB
The M in MEAN
Live! 360 Orlando 2015
VSM03 - Workshop: Busy Developer's Guide to MEANJS - Ted NewardCopyright (c) 2015 Neward & Associates. All rights reserved.This presentation is intended for informational use only.
MongoDB
Document‐oriented
MongoDB
MongoDB: document‐oriented– BSON documents
– JavaScript query language
– map/reduce, server‐side execution
– master/slave replication; sharding
– drivers for most languages
– C++ implementation
– http://www.mongodb.org
– Upshot: useful for most things a small "dynamically‐typed" RDBMS would be useful for
Live! 360 Orlando 2015
VSM03 - Workshop: Busy Developer's Guide to MEANJS - Ted NewardCopyright (c) 2015 Neward & Associates. All rights reserved.This presentation is intended for informational use only.
MongoDB Basics
Gotta start somewhere...
Basics
MongoDB runs as (one or more) servers, typically 1/machine– Like most databases, programs connect to the server
– This means Mongo is architecturally similar to the RDBMS
nothing new/different to learn about that
– "mongo" is a local (JavaScript) shell to MongoDB
used for all MongoDB documentation examples
– Contrary to RDBMS, there is no per‐database schema
the document model is the schema
– Contrary to RDBMS, things are built "on demand"
databases, collections in particular
Live! 360 Orlando 2015
VSM03 - Workshop: Busy Developer's Guide to MEANJS - Ted NewardCopyright (c) 2015 Neward & Associates. All rights reserved.This presentation is intended for informational use only.
Basics
Connect to a local server
mongo
Connect to a remote server on port 27017 to the foodb database
mongo myotherserver:27017/foodb
mongo ‐‐host myotherserver ‐‐port 27017
Basics
MongoDB server holds 0..n databases– "database" = named instance of collections
– "collection" = named instance of documents
Live! 360 Orlando 2015
VSM03 - Workshop: Busy Developer's Guide to MEANJS - Ted NewardCopyright (c) 2015 Neward & Associates. All rights reserved.This presentation is intended for informational use only.
Basics
List all the databases on the server
MongoDB shell version: 2.4.9connecting to: localhost> show dbslocal 0.078125GB>
Use (and/or create) a database
> show dbslocal 0.078125GB> use hrappswitched to db hrapp
Basics
List all the collections in a database
> use hrappswitched to db hrapp> show collections>
Live! 360 Orlando 2015
VSM03 - Workshop: Busy Developer's Guide to MEANJS - Ted NewardCopyright (c) 2015 Neward & Associates. All rights reserved.This presentation is intended for informational use only.
Basics
MongoDB data model is all "documents"– "document" = collection of name‐value pairs
– documents generally take the form of JSON‐like data
– think "Map<name, value>" where values can be one of:
•integer, double•boolean•strings, dates, regular expressions•array•object ID's (OIDs)•binary data•code (!)
Basics
Insert vs Update ‐‐> "Upsert"– Document's uniqueness described by "_id" field
– When document is stored, if it has an _id, update it
– ... if not, insert it
Mongo will generate an _id on demand‐‐let it!
Live! 360 Orlando 2015
VSM03 - Workshop: Busy Developer's Guide to MEANJS - Ted NewardCopyright (c) 2015 Neward & Associates. All rights reserved.This presentation is intended for informational use only.
Basics
Of course, MongoDB also supports querying for documents– Find a single document matching specific criteria
•document passed as query•"_id" is perfectly acceptable as criteria•returns null on failure
– Find a set of documents, either by query/predicate or complex query
first is a "query by example" query; any objects which match all of the criteria in the prototype will be returnedsecond is a "query by document"; pass in a document that contains some simple expressions for comparison
Basics
Operators$lt, $gt, $lte, $gte $ne: less‐than, greater‐than, less‐than‐or‐equal, greater‐than‐or‐equal, not‐equals
$in, $nin: specify array of possible matches ("IN"); "!IN"
$all: like $in, but must match all values
$size: specify size of an array
$exists: existence (or lack) of a field
$where: specify a "WHERE"‐style clause
{ $where : "this.field > 3" }
Combine operators to specify range{ "field" : { $gt : 1, $lt : 5 } } == 1 < field < 5
Live! 360 Orlando 2015
VSM03 - Workshop: Busy Developer's Guide to MEANJS - Ted NewardCopyright (c) 2015 Neward & Associates. All rights reserved.This presentation is intended for informational use only.
Basics
More querying options:– Find documents via predicate clause
can also use "dot notation" to query elements contained from toplevel document into subobjects
– Find documents via code block
takes a Java/ECMAScript code block, executes it on the server, and returns the list of objects that are yielded from the code block's execution
Exercise
Give it a spin
Live! 360 Orlando 2015
VSM03 - Workshop: Busy Developer's Guide to MEANJS - Ted NewardCopyright (c) 2015 Neward & Associates. All rights reserved.This presentation is intended for informational use only.
Exercise
Things to try right now:– download, install MongoDB on your laptop
or, provision a new database in the cloud
– "admin" it:
•connect to a MongoDB server from the "mongo" client•create a new database (call it "personsDB")•use that database•create a new collection (call it "persons")•use that collection•add a person or two to the collection•list them all
– "npm install mongodb"
– use Mongo to store/retrieve the persons
AngularJS
The A in MEAN
Live! 360 Orlando 2015
VSM03 - Workshop: Busy Developer's Guide to MEANJS - Ted NewardCopyright (c) 2015 Neward & Associates. All rights reserved.This presentation is intended for informational use only.
Overview and Introduction
What's this 'Angular' thing, anyway?
Introduction
AngularJS is an opinionated Single‐Page Application MVC JavaScript framework– Opionated: very strong design decisions
– Single‐Page App: all the action happens in one HTML file
– MVC: Model‐View Controller separation of concerns
•All of the application (views, etc) downloaded at once•Extensively modifies the DOM at runtime
– Dependency‐injected
– Testable
– JavaScript
– Framework
Live! 360 Orlando 2015
VSM03 - Workshop: Busy Developer's Guide to MEANJS - Ted NewardCopyright (c) 2015 Neward & Associates. All rights reserved.This presentation is intended for informational use only.
Concepts
MVC is alive and well– In fact, Angular tries to be even more rigorous about it
•Views: HTML and CSS•Controllers: Javascript•Models: JSON objects
Concepts
Separation of UI and logic– jQuery and other frameworks see a lot of "intent bleed"
•DOM manipulation in callbacks•data manipulation in DOM‐related code•it's just "too easy" to break the rules
Live! 360 Orlando 2015
VSM03 - Workshop: Busy Developer's Guide to MEANJS - Ted NewardCopyright (c) 2015 Neward & Associates. All rights reserved.This presentation is intended for informational use only.
Concepts
Testing, testing, testing– Web applications have no excuse to be not tested
•HTML is easily parsed and examined•HTTP is trivial to fake/mock•libraries (Selenium) to handle the heavy lifting
Concepts
The ubiquitous TODO app: HTML
<body><h2>Todo</h2><div ng‐controller="TodoController">
<span>{{remaining()}} of {{todos.length}} remaining</span>[ <a href="" ng‐click="archive()">archive</a> ]<ul class="unstyled">
<li ng‐repeat="todo in todos"><input type="checkbox" ng‐model="todo.done"><span class="done‐{{todo.done}}">{{todo.text}}</span>
</li></ul><form ng‐submit="addTodo()">
<input type="text" ng‐model="todoText" size="30"placeholder="add new todo here">
<input class="btn‐primary" type="submit" value="add"></form>
</div></body>
Live! 360 Orlando 2015
VSM03 - Workshop: Busy Developer's Guide to MEANJS - Ted NewardCopyright (c) 2015 Neward & Associates. All rights reserved.This presentation is intended for informational use only.
Concepts
The ubiquitous TODO app: Javascript (1/2)
var todoApp = angular.module('TodoApp', []);
todoApp.controller('TodoController',['$scope',function ($scope) {
$scope.todos = [{text:'learn angular', done:true},{text:'build an angular app', done:false}];
$scope.addTodo = function() {$scope.todos.push({text:$scope.todoText, done:false});$scope.todoText = '';
};// ... continued
Concepts
The ubiquitous TODO app: Javascript (2/2)
// ... continued$scope.remaining = function() {
var count = 0;angular.forEach($scope.todos, function(todo) {
count += todo.done ? 0 : 1;});return count;
};$scope.archive = function() {
var oldTodos = $scope.todos;$scope.todos = [];angular.forEach(oldTodos, function(todo) {
if (!todo.done) $scope.todos.push(todo);});
};}]);// {{## BEGIN js‐2 ##}}
Live! 360 Orlando 2015
VSM03 - Workshop: Busy Developer's Guide to MEANJS - Ted NewardCopyright (c) 2015 Neward & Associates. All rights reserved.This presentation is intended for informational use only.
Concepts
The ubiquitous TODO app: CSS
.done‐true {text‐decoration: line‐through;color: grey;
}
Concepts
Angular is built using some core concepts:– Modules: grouped JavaScript functionality
– Models: the data elements that represent the current state
– Controllers: application logic, wiring models to views
– Views: serve two purposes:
•present the model data to the user•gather user interactions and data
– Services: specialized objects used to perform specific actions
•fetch data•provide useful algorithms
– Providers: factory objects that produce service objects
– Directives: "custom HTML tags" specific to a purpose
Live! 360 Orlando 2015
VSM03 - Workshop: Busy Developer's Guide to MEANJS - Ted NewardCopyright (c) 2015 Neward & Associates. All rights reserved.This presentation is intended for informational use only.
Concepts
Angular additional concepts:– Templates: HTML with additional markup
– Expressions: computed values
– Scope: hierarchical data collections
– Compiler: parses the template and instantiates directives and expressions
– Filter: formats the value of an expression for display to the user
MEANJS
An all‐in‐one package
Live! 360 Orlando 2015
VSM03 - Workshop: Busy Developer's Guide to MEANJS - Ted NewardCopyright (c) 2015 Neward & Associates. All rights reserved.This presentation is intended for informational use only.
MEANJS
MEANJS is a Node package that wires up most all of this– http://meanjs.org
– npm install ‐g meanjs
– Uses Bower and Grunt (two "build" tools for JS)
•Bower is npm for the client side•Grunt is a "script runner" a la Ant or Make
– Also can make use of Yo to do scaffolding
Alternatives
There are a few alternatives to consider– SailsJS (http://www.sailsjs.org)
– LoopbackJS (http://loopback.io)(http://strongloop.com)
– Meteor (http://www.meteor.com)
Live! 360 Orlando 2015
VSM03 - Workshop: Busy Developer's Guide to MEANJS - Ted NewardCopyright (c) 2015 Neward & Associates. All rights reserved.This presentation is intended for informational use only.
Summary
MEAN is "just" a way of building an app– emphasizes rapidity
– powerful prototyping tool
– production‐ready/capable
... but it's not a silver bullet– Node doesn't eliminate all concurrency issues
– MongoDB has its own share of issues
– AngularJS is changing, and is not easy
Summary
Consider alternatives:– MSPA (Mongo, Scala, Play, Angular)
– M.NF#A (Mongo, .NET, F#, Angular)
– CEAN (CouchDB, NodeJS, Express, Angular)
– MEAEK (Mongo, Express, Angular, EmberJS, KnockoutJS)
– MEAD (Mongo, Express, Angular, Durandal)
– ... you get the idea