Node.js - Server Side Javascript

61
Milano, 20 gennaio 2017 Server-Side JavaScript a cura di: Matteo Pio Napolitano Angelo Giuffredi

Transcript of Node.js - Server Side Javascript

Page 1: Node.js - Server Side Javascript

Milano, 20 gennaio 2017

Server-Side JavaScripta cura di:

Matteo Pio Napolitano Angelo Giuffredi

Page 2: Node.js - Server Side Javascript

Planning

• Server-Side JavaScript

• Node.js

• Locomotive.js, MVC framework

Page 3: Node.js - Server Side Javascript

JavaScript - Evolution

The 4th edition of ECMA-262 was abandoned due to disagreement about the features of the scripting language

Page 4: Node.js - Server Side Javascript

JavaScript Client-Side and Server-Side

• JavaScript Client-Side comprende il linguaggio di base e gli oggetti rilevanti per l'esecuzione in un browser. Lo script è integrato direttamente nelle pagine HTML ed è interpretato dal browser in fase di esecuzione.

• JavaScript Server-Side comprende il linguaggio di base ma non le funzionalità di manipolazione del DOM. Consente l'accesso a database, file system, web-server features e il deploy avviene solitamente solo dopo la compilazione.

Page 5: Node.js - Server Side Javascript

<script> function myFunction() { var x, text;

// Get the value of the input field with id="numb" x = document.getElementById("numb").value;

// If x is Not a Number if (isNaN(x)) { text = "Input not valid"; } else { text = "Input OK"; } document.getElementById("demo").innerHTML = text; } </script>

JavaScript Client-Side

Page 6: Node.js - Server Side Javascript

var http = require('http'); var server = http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello World'); }) server.listen(1337, '127.0.0.1'); console.log('Server running at http://127.0.0.1:1337/');

JavaScript Server-Side

Page 7: Node.js - Server Side Javascript

JS Server Implementation Comparison

Product Description Benefits Limitations

Google Apps Script

Cloud based scripting language

• Easy to learn • Community-based support

model• Runs only in Google Cloud

SilkJSConsole application that wraps the V8 JavaScript

engine

• Fastest HTTP Syncronous implementation

• Only for Unix • Now Deprecated

DecafJS JavaScript engine developed entirely in Java

• Synchronous and threaded HTTP implementation

• JavaScript is compiled to Java byte

• Small Community • No Package Manager

Node.jsJavaScript runtime built on Chrome's V8 JavaScript

engine

• Event-driven and non-blocking I/O model

• Package ecosystem (NPM) • Crowded community

• Backward compatibility for modules and packages

• It depends heavily on npm

Page 8: Node.js - Server Side Javascript

What is V8 JS Engine?• V8 is Google's open source high-performance JavaScript engine,

written in C++ and used in Chromium, Node.js and multiple other embedding applications.

• V8 implements ECMAScript as specified in ECMA-262. and runs on Windows XP or later, Mac OS X 10.5+, and Linux systems that use IA-32, ARM or MIPS processors.

• V8 can run standalone, or can be embedded into any C++ application.

• V8 compiles and executes JavaScript source code, handles memory allocation for objects, and garbage collects objects it no longer needs.

• V8's stop-the-world, generational, accurate garbage collector is one of the keys to V8's performance.

Page 9: Node.js - Server Side Javascript

What is V8 JS Engine?• V8 compiles JavaScript to native machine code

before executing it. The compiled code is additionally optimized (and re-optimized) dynamically at runtime, based on heuristics of the code's execution profile. Optimization techniques used include inlining, elision of expensive runtime properties, and inline caching, among many others.

Read more: https://en.wikipedia.org/wiki/V8_(JavaScript_engine)

Page 10: Node.js - Server Side Javascript

What is V8 JS Engine?

Page 11: Node.js - Server Side Javascript

V8 JS Engine - Hello WorldThis Hello World example takes a JavaScript statement as a string argument, executes it as JavaScript code, and prints the result to standard out.

• An isolate is a VM instance with its own heap.

• A local handle is a pointer to an object. All V8 objects are accessed using handles, they are necessary because of the way the V8 garbage collector works.

• A handle scope can be thought of as a container for any number of handles.

• A context is an execution environment that allows separate, unrelated, JavaScript code to run in a single instance of V8.

(Read more: https://github.com/v8/v8/wiki/Getting%20Started%20with%20Embedding)

Code at: https://goo.gl/Ho11MF

Page 12: Node.js - Server Side Javascript

Node.js“Node.js® is a JavaScript runtime built on Chrome's V8 JavaScript engine. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient. Node.js' package ecosystem, npm, is the largest ecosystem of open source libraries in the

world.”

Read more: https://nodejs.org

Page 13: Node.js - Server Side Javascript

Node.js - How does it works

Node.js è integralmente event-driven. Il server è costituito da un singolo processo che elabora un

evento dopo l'altro.

Image from: http://softwareengineeringdaily.com/

Page 14: Node.js - Server Side Javascript

Node.js - How does it works

Page 15: Node.js - Server Side Javascript

Node.js - How does it works

Image from: https://charwangles.com/

Page 16: Node.js - Server Side Javascript

Event-Driven ProgrammingLa Programmazione ad Eventi è un paradigma di programmazione in cui il flusso di esecuzione del

software è determinato da eventi quali le azioni degli utenti, ricezione di output da sensori, o messaggi da

altri programmi / thread.

In un'applicazione event-driven, vi è generalmente un ciclo principale che intercetta gli eventi, e

quindi attiva una funzione di callback quando viene rilevato uno di quegli eventi.

Page 17: Node.js - Server Side Javascript

Event-Driven Programming un esempio

var fs = require(‘fs’); var path = require(‘path’);

fs.readdir(currentDirPath, function (err, files) { // QUESTO CODICE VIENE ESEGUITO IN MANIERA // ASINCRONA RISPETTO AL CICLO DI ESECUZIONE // PRINCIPALE if (err) {

throw new Error(err); }

files.forEach(function (name) { // do something

}); });

Page 18: Node.js - Server Side Javascript

Node.js - Development• Buoni propositi:

• dal giorno 1, l’applicazione dovrebbe essere scritta come un sistema distribuito (o distribuibile).

• Evitare di scrivere del JavaScript poco leggibile, quindi potremmo farci aiutare da alcuni tool come CoffeeScript, FlowType e TypeScript (dipende se e come possiamo usarli).

• Fate attenzione ai node_modules che si utilizzano.

Page 19: Node.js - Server Side Javascript

Node.js - Development• Gestione della memoria:

• La memoria non viene liberata al termine di un loop (inteso come ciclo dell’event loop principale).

• Il memory footprint dell’applicazione tende ad aumentare con lo scorrere del tempo.

• Aiutare il GC deallocando esplicitamente quando possibile.

Page 20: Node.js - Server Side Javascript

Node.js - Development• Aiutiamo la Garbage Collection

Page 21: Node.js - Server Side Javascript

Node.js ECMAScript 2015 (ES6) and beyond

All ECMAScript 2015 (ES6) features are split into three groups for shipping, staged, and in progress features

Which features ship with which Node.js version by default?

Please visit

http://node.green/

Page 22: Node.js - Server Side Javascript

Node.js - How to get started

• Install Node.js and NPM

• Create a script

• Execute it!

Page 23: Node.js - Server Side Javascript

Node.js - Install

NPM viene installato insieme a Node.js Su alcuni sistemi Unix è disponibile come package standalone

Page 24: Node.js - Server Side Javascript

Node.js - Your first script

console.log(“Hello Node!”);

for(var i = 0; i < 5; i++) { console.log(“This is the log line ” + i);

}

firstscript.js

Page 25: Node.js - Server Side Javascript

Node.js - Execution$ node firstscript.js

Page 26: Node.js - Server Side Javascript

Node.js - Fundamentals• process – oggetto che contiene informazioni e

metodi relativi al processo corrente process.stdout, process.stderr, process.stdin, process.argv, process.env

• console – consente di stampare su stdout e stderr• require() – funzione che consente il caricamento di

un modulo• module – oggetto che fa riferimento al modulo

corrente

Page 27: Node.js - Server Side Javascript

Node.js - Moduli• I moduli sono componenti che permettono di estendere le

funzionalità di Node, possono essere considerati come “librerie”

• Un modulo può essere incluso in uno script tramite il metodo globale require(‘module’)

• Node fornisce dei moduli “nativi” che possono essere richiamati con il loro nome

Page 28: Node.js - Server Side Javascript

Node.js - Moduli

module.exports = function() { this.hello = function(){ return ‘hello’; }; this.bye = function(){ return ‘bye’; }

}

var bar = require(‘./bar.js’) console.log(bar.hello()) // prints ‘hello’ console.log(bar.bye()) // prints ‘bye’

bar.js

foo.js

Page 29: Node.js - Server Side Javascript
Page 30: Node.js - Server Side Javascript

NPM Node Package Manager

“npm is the package manager for JavaScript. Find, share, and reuse packages of code from hundreds of thousands of developers — and

assemble them in powerful new ways.”

Read more: https://www.npmjs.com/

Page 31: Node.js - Server Side Javascript

NPM - Usage

cli-color: Colors, formatting and other goodies for the console.

Read more: https://www.npmjs.com/package/cli-color

Page 32: Node.js - Server Side Javascript

NPM - Using a package

var clc = require(‘cli-color');

console.log(“Hello Node!”);

for(var i = 0; i < 5; i++) { if(i%2 == 0) {

console.log(clc.red(“The line ” + i + “ is in red”)); } else {

console.log(clc.blue(“The line ” + i + “ is in blue”)); }

}

secondscript.js

Page 33: Node.js - Server Side Javascript

NPM - Using a package$ node secondscript.js

Page 34: Node.js - Server Side Javascript

NPM - Dipendenze• Quando si crea un’applicazione Node è sempre

opportuno gestire le dipendenze da librerie esterne tramite NPM

• La nostra applicazione può essere inoltre “firmata” tramite NPM stesso grazie all’aggiunta di metadati

• L’istruzione npm init si occupa di creare un file package.json (anche editabile in seguito) che contiene tutte le informazioni relative a dipendenze e metadati

Page 35: Node.js - Server Side Javascript

NPM - Dipendenze

Page 36: Node.js - Server Side Javascript
Page 37: Node.js - Server Side Javascript

Node - Create a Web Server

var http = require('http'); var server = http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello World'); }) server.listen(8088, '127.0.0.1'); console.log('Server running at http://127.0.0.1:8088/');

server.js

Page 38: Node.js - Server Side Javascript

Node - Create a Web Server

$ node server.js

Page 39: Node.js - Server Side Javascript

Node.js - Development• Callback Hell, numerose funzioni vengono eseguite al

termine di un’altra:

• Molte librerie/funzioni, native e di terze parti, vengono eseguite in modo asincrono (coperative multitasking)

• Librerie che forniscono un API per la gestione delle promise (es: q) si rendono necessarie

• Difficile mantenere uno scaffolding sensato

Page 40: Node.js - Server Side Javascript

Node.js - Development• Callback Hell, numerose funzioni vengono eseguite

al termine di un’altra. In successione.

Page 41: Node.js - Server Side Javascript

Node.js - Development• Callback Hell, le promise ci vengono in aiuto.

Page 42: Node.js - Server Side Javascript

Node.js - Development• Applicazioni che supportano: HTTP || WS || TCP

• HTTP framework: express.js. Introduce l’architettura a middleware (in php: relayphp)

• WS: socket.io, sock.js. Purtroppo ancora non è banale mantenere una WS aperta su browser mobile (e vecchi browser)

• TCP: fare cose con Redis

Page 43: Node.js - Server Side Javascript

Node.js - Development• express.js, Hello world!

Page 44: Node.js - Server Side Javascript

Locomotive.js“Locomotive is a web framework for Node.js.

Locomotive supports MVC patterns, RESTful routes, and convention over configuration, while integrating seamlessly with any database and template engine. Locomotive builds on Express, preserving the power

and simplicity you've come to expect from Node.”

Read more: http://locomotivejs.org/

Page 45: Node.js - Server Side Javascript

Locomotive.js - Intro• Framework per lo sviluppo full stack di web

application in JavaScript

• Built-In Web server

• Costruito come estensione del framework Express “Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications.”

• MVC Support

Page 46: Node.js - Server Side Javascript

Locomotive.js - MVC

Image from: https://smist08.wordpress.com/

Page 47: Node.js - Server Side Javascript

Locomotive.js Directory Structure

app/controllersContains the controllers that handle requests sent to an application.

app/modelsContains the models for accessing and storing data in a database.

app/viewsContains the views and layouts that are rendered by an application.

configConfiguration for the application, including routes, databases, etc.

config/environmentsEnvironment-specific configuration. For example, development and production are two environments that require different settings.

config/initializersInitialization code that is executed before the applications starts.

publicStatic files and compiled assets served by the application.

Page 48: Node.js - Server Side Javascript

Locomotive.js Initialization flow

1. Configure the Environment

2. Invoke Initializers

3. Draw Routes

4. Start HTTP Server

Page 49: Node.js - Server Side Javascript

Locomotive.js - server.js

Page 50: Node.js - Server Side Javascript

Locomotive.js - Controller

var PhotosController = new Controller();

// this is an Action PhotosController.show = function() { var self = this; models.Photo.findOne({ where: { id: 2 } })

.then(function (_photo) { self.photo = _photo; self.render(); });

}

module.exports = PhotosController;

app/controllers/photosController.js

Page 51: Node.js - Server Side Javascript

Locomotive.js - View

<% if (photo) { %> <h2><%= photo.name %></h2> <% } %>

app/views/photos/show.html.ejs

Locomotive.js di default è pre-configurato per l’utilizzo di EJS Embedded JavaScript templates for Node

Page 52: Node.js - Server Side Javascript

Locomotive.js - Model

?La componente Model non ha una struttura standard in quanto ogni applicazione definisce i propri criteri

per la manipolazione dei dati

Page 53: Node.js - Server Side Javascript

Locomotive.js - Router

this.match('showphoto/:id', { controller: 'photo', action: 'show'

});

will cause PhotosController's show() action to handle requests for URLs which match the pattern. Example URLs

/showphoto/123 /showphoto/89976

config/routes.js

Page 54: Node.js - Server Side Javascript

Node.js - Production

• Normalmente i demoni muoiono se vanno in errore -> bisogna trovare un meccanismo per riavviarli

Page 55: Node.js - Server Side Javascript

Node.js - Production• PM2, è il process manager che tutti vorremmo:

• supervisord on steroids per node.js.

• deploy con 0s di downtime.

• monitoring in locale e tramite interfaccia web.

• Progetto maturo e mantenuto.

Page 56: Node.js - Server Side Javascript

Node.js - ProductionPossiamo lanciare in automatica n demoni, dove n è il numero di core del sistema

Page 57: Node.js - Server Side Javascript

Node.js - Production

Possiamo leggere i log in tempo reale

Page 58: Node.js - Server Side Javascript

Node.js - ProductionSe la nostra applicazione può essere raggiunta tramite HTTP allora è buona norma usare nginx come proxy.

Page 59: Node.js - Server Side Javascript

https://goo.gl/G9mHkoSample Project Repository on Github

Page 60: Node.js - Server Side Javascript

Conclusioni

Popular Sites using Node.js

• Flickr.com • Groupon.com • Coursera.org • Linkedin.com • …. • ….

Page 61: Node.js - Server Side Javascript

Grazie per l’attenzione