Node.js - Server Side Javascript

Post on 13-Apr-2017

132 views 5 download

transcript

Milano, 20 gennaio 2017

Server-Side JavaScripta cura di:

Matteo Pio Napolitano Angelo Giuffredi

Planning

• Server-Side JavaScript

• Node.js

• Locomotive.js, MVC framework

JavaScript - Evolution

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

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.

<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

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

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

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.

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)

What is V8 JS Engine?

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

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

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/

Node.js - How does it works

Node.js - How does it works

Image from: https://charwangles.com/

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.

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

}); });

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.

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.

Node.js - Development• Aiutiamo la Garbage Collection

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/

Node.js - How to get started

• Install Node.js and NPM

• Create a script

• Execute it!

Node.js - Install

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

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

Node.js - Execution$ node firstscript.js

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

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

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

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/

NPM - Usage

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

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

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

NPM - Using a package$ node secondscript.js

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

NPM - Dipendenze

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

Node - Create a Web Server

$ node server.js

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

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

al termine di un’altra. In successione.

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

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

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

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/

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

Locomotive.js - MVC

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

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.

Locomotive.js Initialization flow

1. Configure the Environment

2. Invoke Initializers

3. Draw Routes

4. Start HTTP Server

Locomotive.js - server.js

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

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

Locomotive.js - Model

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

per la manipolazione dei dati

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

Node.js - Production

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

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.

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

Node.js - Production

Possiamo leggere i log in tempo reale

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

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

Conclusioni

Popular Sites using Node.js

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

Grazie per l’attenzione