An overview of technologies and best practices for the development of a full-stack web application using JavaScript. How to realize an entire Application Server with a single programming language, the use of event-driven logic and the potential of Node.js.
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)
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/
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.
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
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
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
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
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.
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
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
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.
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.