SlideShare a Scribd company logo
1 of 61
Download to read offline
Milano, 20 gennaio 2017
Server-Side JavaScript
a 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
SilkJS
Console 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.js
JavaScript 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 World
This 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 Programming
La 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/controllers
Contains the controllers that handle requests sent to an application.
app/models
Contains the models for accessing and storing data in a database.
app/views
Contains the views and layouts that are rendered by an application.
config
Configuration for the application, including routes, databases, etc.
config/environments
Environment-specific configuration. For example, development and
production are two environments that require different settings.
config/initializers
Initialization code that is executed before the applications starts.
public
Static 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 - Production
Possiamo 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 - Production
Se la nostra applicazione può essere raggiunta tramite
HTTP allora è buona norma usare nginx come proxy.
https://goo.gl/G9mHko
Sample Project Repository on Github
Conclusioni
Popular Sites using Node.js
• Flickr.com
• Groupon.com
• Coursera.org
• Linkedin.com
• ….
• ….
Grazie per l’attenzione

More Related Content

What's hot

High specialized vm on open stack cloud
High specialized vm on open stack cloudHigh specialized vm on open stack cloud
High specialized vm on open stack cloudGabriele Baldoni
 
Back to the Future: Migrare da WebForm ad ASP.NET Core gradualmente
Back to the Future: Migrare da WebForm ad ASP.NET Core gradualmente Back to the Future: Migrare da WebForm ad ASP.NET Core gradualmente
Back to the Future: Migrare da WebForm ad ASP.NET Core gradualmente Andrea Dottor
 
Blazor ha vinto? Storie di casi reali
Blazor ha vinto? Storie di casi realiBlazor ha vinto? Storie di casi reali
Blazor ha vinto? Storie di casi realiAndrea Dottor
 
Creare API pubbliche, come evitare gli errori comuni
Creare API pubbliche, come evitare gli errori comuniCreare API pubbliche, come evitare gli errori comuni
Creare API pubbliche, come evitare gli errori comuniAndrea Dottor
 
Livin' with Docker - dallo sviluppo alla produzione
Livin' with Docker - dallo sviluppo alla produzioneLivin' with Docker - dallo sviluppo alla produzione
Livin' with Docker - dallo sviluppo alla produzionegiacomos
 
06 Android - lavorare in background
06 Android - lavorare in background06 Android - lavorare in background
06 Android - lavorare in backgroundspawn150
 
Javascript task automation
Javascript task automationJavascript task automation
Javascript task automationDotNetCampus
 
ASP .NET Core hands-on
ASP .NET Core hands-onASP .NET Core hands-on
ASP .NET Core hands-onugidotnet
 
Java EE facile con Spring Boot - Luigi Bennardis - Codemotion Roma 2015
Java EE facile con Spring Boot - Luigi Bennardis - Codemotion Roma 2015Java EE facile con Spring Boot - Luigi Bennardis - Codemotion Roma 2015
Java EE facile con Spring Boot - Luigi Bennardis - Codemotion Roma 2015Codemotion
 
Closure Visto Da Vicino
Closure Visto Da VicinoClosure Visto Da Vicino
Closure Visto Da Vicinodavide ficano
 
Introduzione pratica a docker, da chi lo ha appena conosciuto
Introduzione pratica a docker, da chi lo ha appena conosciutoIntroduzione pratica a docker, da chi lo ha appena conosciuto
Introduzione pratica a docker, da chi lo ha appena conosciutoDaniele Megna
 
MongoDB User Group Padova - Overviews iniziale su MongoDB
MongoDB User Group Padova - Overviews iniziale su MongoDBMongoDB User Group Padova - Overviews iniziale su MongoDB
MongoDB User Group Padova - Overviews iniziale su MongoDBStefano Dindo
 

What's hot (20)

High specialized vm on open stack cloud
High specialized vm on open stack cloudHigh specialized vm on open stack cloud
High specialized vm on open stack cloud
 
Back to the Future: Migrare da WebForm ad ASP.NET Core gradualmente
Back to the Future: Migrare da WebForm ad ASP.NET Core gradualmente Back to the Future: Migrare da WebForm ad ASP.NET Core gradualmente
Back to the Future: Migrare da WebForm ad ASP.NET Core gradualmente
 
Javascript
JavascriptJavascript
Javascript
 
Blazor ha vinto? Storie di casi reali
Blazor ha vinto? Storie di casi realiBlazor ha vinto? Storie di casi reali
Blazor ha vinto? Storie di casi reali
 
Creare API pubbliche, come evitare gli errori comuni
Creare API pubbliche, come evitare gli errori comuniCreare API pubbliche, come evitare gli errori comuni
Creare API pubbliche, come evitare gli errori comuni
 
Many Designs Elements
Many Designs ElementsMany Designs Elements
Many Designs Elements
 
Livin' with Docker - dallo sviluppo alla produzione
Livin' with Docker - dallo sviluppo alla produzioneLivin' with Docker - dallo sviluppo alla produzione
Livin' with Docker - dallo sviluppo alla produzione
 
Logging
LoggingLogging
Logging
 
06 Android - lavorare in background
06 Android - lavorare in background06 Android - lavorare in background
06 Android - lavorare in background
 
Infrastructure as Data
Infrastructure as DataInfrastructure as Data
Infrastructure as Data
 
Javascript task automation
Javascript task automationJavascript task automation
Javascript task automation
 
Hacking in action - 1
Hacking in action - 1Hacking in action - 1
Hacking in action - 1
 
REST con Jersey
REST con JerseyREST con Jersey
REST con Jersey
 
Node and the Cloud
Node and the CloudNode and the Cloud
Node and the Cloud
 
XPages Tips & Tricks, #dd13
XPages Tips & Tricks, #dd13XPages Tips & Tricks, #dd13
XPages Tips & Tricks, #dd13
 
ASP .NET Core hands-on
ASP .NET Core hands-onASP .NET Core hands-on
ASP .NET Core hands-on
 
Java EE facile con Spring Boot - Luigi Bennardis - Codemotion Roma 2015
Java EE facile con Spring Boot - Luigi Bennardis - Codemotion Roma 2015Java EE facile con Spring Boot - Luigi Bennardis - Codemotion Roma 2015
Java EE facile con Spring Boot - Luigi Bennardis - Codemotion Roma 2015
 
Closure Visto Da Vicino
Closure Visto Da VicinoClosure Visto Da Vicino
Closure Visto Da Vicino
 
Introduzione pratica a docker, da chi lo ha appena conosciuto
Introduzione pratica a docker, da chi lo ha appena conosciutoIntroduzione pratica a docker, da chi lo ha appena conosciuto
Introduzione pratica a docker, da chi lo ha appena conosciuto
 
MongoDB User Group Padova - Overviews iniziale su MongoDB
MongoDB User Group Padova - Overviews iniziale su MongoDBMongoDB User Group Padova - Overviews iniziale su MongoDB
MongoDB User Group Padova - Overviews iniziale su MongoDB
 

Viewers also liked

Viewers also liked (7)

Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
Migrare a Symfony 3
Migrare a Symfony 3Migrare a Symfony 3
Migrare a Symfony 3
 
Full-Stack JavaScript with Node.js
Full-Stack JavaScript with Node.jsFull-Stack JavaScript with Node.js
Full-Stack JavaScript with Node.js
 
Introduction to Node.JS
Introduction to Node.JSIntroduction to Node.JS
Introduction to Node.JS
 
Introduction to JPA Framework
Introduction to JPA FrameworkIntroduction to JPA Framework
Introduction to JPA Framework
 
Building Web Apps with Express
Building Web Apps with ExpressBuilding Web Apps with Express
Building Web Apps with Express
 
Node.js - Best practices
Node.js  - Best practicesNode.js  - Best practices
Node.js - Best practices
 

Similar to Node.js - Server Side Javascript

Node js dev day napoli 2016
Node js dev day napoli 2016Node js dev day napoli 2016
Node js dev day napoli 2016Michele Nasti
 
Roma linuxday 2013 - nodejs
Roma linuxday 2013 - nodejsRoma linuxday 2013 - nodejs
Roma linuxday 2013 - nodejsClaudio Mignanti
 
Simple Cloud API: accesso semplificato al cloud computing
Simple Cloud API: accesso semplificato al cloud computingSimple Cloud API: accesso semplificato al cloud computing
Simple Cloud API: accesso semplificato al cloud computingFrancesca1980
 
Antica presentazione AJAX
Antica presentazione AJAXAntica presentazione AJAX
Antica presentazione AJAXTommaso Torti
 
Androidsdk appinventor
Androidsdk appinventorAndroidsdk appinventor
Androidsdk appinventorfdizazzo
 
Designing with microservices - Daniele Mondello
Designing with microservices - Daniele MondelloDesigning with microservices - Daniele Mondello
Designing with microservices - Daniele MondelloDaniele Mondello
 
Writing apps for android with .net
Writing apps for android with .net Writing apps for android with .net
Writing apps for android with .net Leonardo Alario
 
Azure dayroma java, il lato oscuro del cloud
Azure dayroma   java, il lato oscuro del cloudAzure dayroma   java, il lato oscuro del cloud
Azure dayroma java, il lato oscuro del cloudRiccardo Zamana
 
Sviluppo Web Agile con Castle Monorail
Sviluppo Web Agile con Castle MonorailSviluppo Web Agile con Castle Monorail
Sviluppo Web Agile con Castle MonorailDotNetMarche
 
I linguaggi del web - seconda edizione (3° giornata)
I linguaggi del web - seconda edizione (3° giornata)I linguaggi del web - seconda edizione (3° giornata)
I linguaggi del web - seconda edizione (3° giornata)Diego La Monica
 
LinuxDay2013 - Web2py: make the web easier
LinuxDay2013 - Web2py: make the web easierLinuxDay2013 - Web2py: make the web easier
LinuxDay2013 - Web2py: make the web easierDavide Marzioni
 
ASP.NET performance optimization
ASP.NET performance optimizationASP.NET performance optimization
ASP.NET performance optimizationAndrea Dottor
 
AngularJS – Reinventare le applicazioni web
AngularJS – Reinventare le applicazioni webAngularJS – Reinventare le applicazioni web
AngularJS – Reinventare le applicazioni webLuca Milan
 

Similar to Node.js - Server Side Javascript (20)

Node js dev day napoli 2016
Node js dev day napoli 2016Node js dev day napoli 2016
Node js dev day napoli 2016
 
Introduzione a Node.js
Introduzione a Node.jsIntroduzione a Node.js
Introduzione a Node.js
 
Web frameworks
Web frameworksWeb frameworks
Web frameworks
 
ASP.NET Core essentials
ASP.NET Core essentialsASP.NET Core essentials
ASP.NET Core essentials
 
Roma linuxday 2013 - nodejs
Roma linuxday 2013 - nodejsRoma linuxday 2013 - nodejs
Roma linuxday 2013 - nodejs
 
Simple Cloud API: accesso semplificato al cloud computing
Simple Cloud API: accesso semplificato al cloud computingSimple Cloud API: accesso semplificato al cloud computing
Simple Cloud API: accesso semplificato al cloud computing
 
DDive - 8.5.2 Xpages - L'evoluzione continua
DDive - 8.5.2 Xpages - L'evoluzione continuaDDive - 8.5.2 Xpages - L'evoluzione continua
DDive - 8.5.2 Xpages - L'evoluzione continua
 
node.js everywhere
node.js everywherenode.js everywhere
node.js everywhere
 
App Engine + Python
App Engine + PythonApp Engine + Python
App Engine + Python
 
Antica presentazione AJAX
Antica presentazione AJAXAntica presentazione AJAX
Antica presentazione AJAX
 
Androidsdk appinventor
Androidsdk appinventorAndroidsdk appinventor
Androidsdk appinventor
 
Designing with microservices - Daniele Mondello
Designing with microservices - Daniele MondelloDesigning with microservices - Daniele Mondello
Designing with microservices - Daniele Mondello
 
Writing apps for android with .net
Writing apps for android with .net Writing apps for android with .net
Writing apps for android with .net
 
Azure dayroma java, il lato oscuro del cloud
Azure dayroma   java, il lato oscuro del cloudAzure dayroma   java, il lato oscuro del cloud
Azure dayroma java, il lato oscuro del cloud
 
Sviluppo Web Agile con Castle Monorail
Sviluppo Web Agile con Castle MonorailSviluppo Web Agile con Castle Monorail
Sviluppo Web Agile con Castle Monorail
 
I linguaggi del web - seconda edizione (3° giornata)
I linguaggi del web - seconda edizione (3° giornata)I linguaggi del web - seconda edizione (3° giornata)
I linguaggi del web - seconda edizione (3° giornata)
 
LinuxDay2013 - Web2py: make the web easier
LinuxDay2013 - Web2py: make the web easierLinuxDay2013 - Web2py: make the web easier
LinuxDay2013 - Web2py: make the web easier
 
MyTask
MyTaskMyTask
MyTask
 
ASP.NET performance optimization
ASP.NET performance optimizationASP.NET performance optimization
ASP.NET performance optimization
 
AngularJS – Reinventare le applicazioni web
AngularJS – Reinventare le applicazioni webAngularJS – Reinventare le applicazioni web
AngularJS – Reinventare le applicazioni web
 

Recently uploaded

Giornata Tecnica da Piave Servizi, 11 aprile 2024 | DISCIPIO Antonio
Giornata Tecnica da Piave Servizi, 11 aprile 2024 | DISCIPIO AntonioGiornata Tecnica da Piave Servizi, 11 aprile 2024 | DISCIPIO Antonio
Giornata Tecnica da Piave Servizi, 11 aprile 2024 | DISCIPIO AntonioServizi a rete
 
Giornata Tecnica da Piave Servizi, 11 aprile 2024 | RENZI Daniele
Giornata Tecnica da Piave Servizi, 11 aprile 2024 | RENZI DanieleGiornata Tecnica da Piave Servizi, 11 aprile 2024 | RENZI Daniele
Giornata Tecnica da Piave Servizi, 11 aprile 2024 | RENZI DanieleServizi a rete
 
Giornata Tecnica da Piave Servizi, 11 aprile 2024 | DI DOMENICO Simone
Giornata Tecnica da Piave Servizi, 11 aprile 2024 | DI DOMENICO SimoneGiornata Tecnica da Piave Servizi, 11 aprile 2024 | DI DOMENICO Simone
Giornata Tecnica da Piave Servizi, 11 aprile 2024 | DI DOMENICO SimoneServizi a rete
 
Giornata Tecnica da Piave Servizi, 11 aprile 2024 | ALBIERO Andrea
Giornata Tecnica da Piave Servizi, 11 aprile 2024 | ALBIERO AndreaGiornata Tecnica da Piave Servizi, 11 aprile 2024 | ALBIERO Andrea
Giornata Tecnica da Piave Servizi, 11 aprile 2024 | ALBIERO AndreaServizi a rete
 
Giornata Tecnica da Piave Servizi, 11 aprile 2024 | CADEI Giovanni
Giornata Tecnica da Piave Servizi, 11 aprile 2024 | CADEI GiovanniGiornata Tecnica da Piave Servizi, 11 aprile 2024 | CADEI Giovanni
Giornata Tecnica da Piave Servizi, 11 aprile 2024 | CADEI GiovanniServizi a rete
 
Giornata Tecnica da Piave Servizi, 11 aprile 2024 | ROMANO' Davide
Giornata Tecnica da Piave Servizi, 11 aprile 2024 | ROMANO' DavideGiornata Tecnica da Piave Servizi, 11 aprile 2024 | ROMANO' Davide
Giornata Tecnica da Piave Servizi, 11 aprile 2024 | ROMANO' DavideServizi a rete
 
Giornata Tecnica da Piave Servizi, 11 aprile 2024 | SERRA Giorgio
Giornata Tecnica da Piave Servizi, 11 aprile 2024 | SERRA GiorgioGiornata Tecnica da Piave Servizi, 11 aprile 2024 | SERRA Giorgio
Giornata Tecnica da Piave Servizi, 11 aprile 2024 | SERRA GiorgioServizi a rete
 

Recently uploaded (7)

Giornata Tecnica da Piave Servizi, 11 aprile 2024 | DISCIPIO Antonio
Giornata Tecnica da Piave Servizi, 11 aprile 2024 | DISCIPIO AntonioGiornata Tecnica da Piave Servizi, 11 aprile 2024 | DISCIPIO Antonio
Giornata Tecnica da Piave Servizi, 11 aprile 2024 | DISCIPIO Antonio
 
Giornata Tecnica da Piave Servizi, 11 aprile 2024 | RENZI Daniele
Giornata Tecnica da Piave Servizi, 11 aprile 2024 | RENZI DanieleGiornata Tecnica da Piave Servizi, 11 aprile 2024 | RENZI Daniele
Giornata Tecnica da Piave Servizi, 11 aprile 2024 | RENZI Daniele
 
Giornata Tecnica da Piave Servizi, 11 aprile 2024 | DI DOMENICO Simone
Giornata Tecnica da Piave Servizi, 11 aprile 2024 | DI DOMENICO SimoneGiornata Tecnica da Piave Servizi, 11 aprile 2024 | DI DOMENICO Simone
Giornata Tecnica da Piave Servizi, 11 aprile 2024 | DI DOMENICO Simone
 
Giornata Tecnica da Piave Servizi, 11 aprile 2024 | ALBIERO Andrea
Giornata Tecnica da Piave Servizi, 11 aprile 2024 | ALBIERO AndreaGiornata Tecnica da Piave Servizi, 11 aprile 2024 | ALBIERO Andrea
Giornata Tecnica da Piave Servizi, 11 aprile 2024 | ALBIERO Andrea
 
Giornata Tecnica da Piave Servizi, 11 aprile 2024 | CADEI Giovanni
Giornata Tecnica da Piave Servizi, 11 aprile 2024 | CADEI GiovanniGiornata Tecnica da Piave Servizi, 11 aprile 2024 | CADEI Giovanni
Giornata Tecnica da Piave Servizi, 11 aprile 2024 | CADEI Giovanni
 
Giornata Tecnica da Piave Servizi, 11 aprile 2024 | ROMANO' Davide
Giornata Tecnica da Piave Servizi, 11 aprile 2024 | ROMANO' DavideGiornata Tecnica da Piave Servizi, 11 aprile 2024 | ROMANO' Davide
Giornata Tecnica da Piave Servizi, 11 aprile 2024 | ROMANO' Davide
 
Giornata Tecnica da Piave Servizi, 11 aprile 2024 | SERRA Giorgio
Giornata Tecnica da Piave Servizi, 11 aprile 2024 | SERRA GiorgioGiornata Tecnica da Piave Servizi, 11 aprile 2024 | SERRA Giorgio
Giornata Tecnica da Piave Servizi, 11 aprile 2024 | SERRA Giorgio
 

Node.js - Server Side Javascript

  • 1. Milano, 20 gennaio 2017 Server-Side JavaScript a cura di: Matteo Pio Napolitano Angelo Giuffredi
  • 2. Planning • Server-Side JavaScript • Node.js • Locomotive.js, MVC framework
  • 3. JavaScript - Evolution The 4th edition of ECMA-262 was abandoned due to disagreement about the features of the scripting language
  • 4. 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.
  • 5. <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
  • 6. 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
  • 7. 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 SilkJS Console 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.js JavaScript 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
  • 8. 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.
  • 9. 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)
  • 10. What is V8 JS Engine?
  • 11. V8 JS Engine - Hello World This 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
  • 12. 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
  • 13. 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/
  • 14. Node.js - How does it works
  • 15. Node.js - How does it works Image from: https://charwangles.com/
  • 16. Event-Driven Programming La 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.
  • 17. 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 }); });
  • 18. 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.
  • 19. 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.

  • 20. Node.js - Development • Aiutiamo la Garbage Collection

  • 21. 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/
  • 22. Node.js - How to get started • Install Node.js and NPM • Create a script • Execute it!
  • 23. Node.js - Install NPM viene installato insieme a Node.js Su alcuni sistemi Unix è disponibile come package standalone
  • 24. 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
  • 25. Node.js - Execution $ node firstscript.js
  • 26. 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
  • 27. 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
  • 28. 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
  • 29.
  • 30. 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/
  • 31. NPM - Usage cli-color: Colors, formatting and other goodies for the console. Read more: https://www.npmjs.com/package/cli-color
  • 32. 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
  • 33. NPM - Using a package $ node secondscript.js
  • 34. 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
  • 36.
  • 37. 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
  • 38. Node - Create a Web Server $ node server.js
  • 39. 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

  • 40. Node.js - Development • Callback Hell, numerose funzioni vengono eseguite al termine di un’altra. In successione.

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

  • 42. 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
  • 43. Node.js - Development • express.js, Hello world!
  • 44. 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/
  • 45. 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
  • 46. Locomotive.js - MVC Image from: https://smist08.wordpress.com/
  • 47. Locomotive.js Directory Structure app/controllers Contains the controllers that handle requests sent to an application. app/models Contains the models for accessing and storing data in a database. app/views Contains the views and layouts that are rendered by an application. config Configuration for the application, including routes, databases, etc. config/environments Environment-specific configuration. For example, development and production are two environments that require different settings. config/initializers Initialization code that is executed before the applications starts. public Static files and compiled assets served by the application.
  • 48. Locomotive.js Initialization flow 1. Configure the Environment 2. Invoke Initializers 3. Draw Routes 4. Start HTTP Server
  • 50. 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
  • 51. 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
  • 52. Locomotive.js - Model ? La componente Model non ha una struttura standard in quanto ogni applicazione definisce i propri criteri per la manipolazione dei dati
  • 53. 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
  • 54. Node.js - Production • Normalmente i demoni muoiono se vanno in errore 
 -> bisogna trovare un meccanismo per riavviarli
 

  • 55. 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.
  • 56. Node.js - Production Possiamo lanciare in automatica n demoni, dove n è il numero di core del sistema
  • 57. Node.js - Production Possiamo leggere i log in tempo reale
  • 58. Node.js - Production Se la nostra applicazione può essere raggiunta tramite HTTP allora è buona norma usare nginx come proxy.
  • 60. Conclusioni Popular Sites using Node.js • Flickr.com • Groupon.com • Coursera.org • Linkedin.com • …. • ….