node.js - server side javascript
TRANSCRIPT
![Page 1: Node.js - Server Side Javascript](https://reader033.vdocuments.mx/reader033/viewer/2022050812/58998efc1a28ab30328b4a03/html5/thumbnails/1.jpg)
Milano, 20 gennaio 2017
Server-Side JavaScripta cura di:
Matteo Pio Napolitano Angelo Giuffredi
![Page 2: Node.js - Server Side Javascript](https://reader033.vdocuments.mx/reader033/viewer/2022050812/58998efc1a28ab30328b4a03/html5/thumbnails/2.jpg)
Planning
• Server-Side JavaScript
• Node.js
• Locomotive.js, MVC framework
![Page 3: Node.js - Server Side Javascript](https://reader033.vdocuments.mx/reader033/viewer/2022050812/58998efc1a28ab30328b4a03/html5/thumbnails/3.jpg)
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](https://reader033.vdocuments.mx/reader033/viewer/2022050812/58998efc1a28ab30328b4a03/html5/thumbnails/4.jpg)
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](https://reader033.vdocuments.mx/reader033/viewer/2022050812/58998efc1a28ab30328b4a03/html5/thumbnails/5.jpg)
<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](https://reader033.vdocuments.mx/reader033/viewer/2022050812/58998efc1a28ab30328b4a03/html5/thumbnails/6.jpg)
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](https://reader033.vdocuments.mx/reader033/viewer/2022050812/58998efc1a28ab30328b4a03/html5/thumbnails/7.jpg)
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](https://reader033.vdocuments.mx/reader033/viewer/2022050812/58998efc1a28ab30328b4a03/html5/thumbnails/8.jpg)
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](https://reader033.vdocuments.mx/reader033/viewer/2022050812/58998efc1a28ab30328b4a03/html5/thumbnails/9.jpg)
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](https://reader033.vdocuments.mx/reader033/viewer/2022050812/58998efc1a28ab30328b4a03/html5/thumbnails/10.jpg)
What is V8 JS Engine?
![Page 11: Node.js - Server Side Javascript](https://reader033.vdocuments.mx/reader033/viewer/2022050812/58998efc1a28ab30328b4a03/html5/thumbnails/11.jpg)
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](https://reader033.vdocuments.mx/reader033/viewer/2022050812/58998efc1a28ab30328b4a03/html5/thumbnails/12.jpg)
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](https://reader033.vdocuments.mx/reader033/viewer/2022050812/58998efc1a28ab30328b4a03/html5/thumbnails/13.jpg)
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](https://reader033.vdocuments.mx/reader033/viewer/2022050812/58998efc1a28ab30328b4a03/html5/thumbnails/14.jpg)
Node.js - How does it works
![Page 15: Node.js - Server Side Javascript](https://reader033.vdocuments.mx/reader033/viewer/2022050812/58998efc1a28ab30328b4a03/html5/thumbnails/15.jpg)
Node.js - How does it works
Image from: https://charwangles.com/
![Page 16: Node.js - Server Side Javascript](https://reader033.vdocuments.mx/reader033/viewer/2022050812/58998efc1a28ab30328b4a03/html5/thumbnails/16.jpg)
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](https://reader033.vdocuments.mx/reader033/viewer/2022050812/58998efc1a28ab30328b4a03/html5/thumbnails/17.jpg)
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](https://reader033.vdocuments.mx/reader033/viewer/2022050812/58998efc1a28ab30328b4a03/html5/thumbnails/18.jpg)
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](https://reader033.vdocuments.mx/reader033/viewer/2022050812/58998efc1a28ab30328b4a03/html5/thumbnails/19.jpg)
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](https://reader033.vdocuments.mx/reader033/viewer/2022050812/58998efc1a28ab30328b4a03/html5/thumbnails/20.jpg)
Node.js - Development• Aiutiamo la Garbage Collection
![Page 21: Node.js - Server Side Javascript](https://reader033.vdocuments.mx/reader033/viewer/2022050812/58998efc1a28ab30328b4a03/html5/thumbnails/21.jpg)
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](https://reader033.vdocuments.mx/reader033/viewer/2022050812/58998efc1a28ab30328b4a03/html5/thumbnails/22.jpg)
Node.js - How to get started
• Install Node.js and NPM
• Create a script
• Execute it!
![Page 23: Node.js - Server Side Javascript](https://reader033.vdocuments.mx/reader033/viewer/2022050812/58998efc1a28ab30328b4a03/html5/thumbnails/23.jpg)
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](https://reader033.vdocuments.mx/reader033/viewer/2022050812/58998efc1a28ab30328b4a03/html5/thumbnails/24.jpg)
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](https://reader033.vdocuments.mx/reader033/viewer/2022050812/58998efc1a28ab30328b4a03/html5/thumbnails/25.jpg)
Node.js - Execution$ node firstscript.js
![Page 26: Node.js - Server Side Javascript](https://reader033.vdocuments.mx/reader033/viewer/2022050812/58998efc1a28ab30328b4a03/html5/thumbnails/26.jpg)
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](https://reader033.vdocuments.mx/reader033/viewer/2022050812/58998efc1a28ab30328b4a03/html5/thumbnails/27.jpg)
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](https://reader033.vdocuments.mx/reader033/viewer/2022050812/58998efc1a28ab30328b4a03/html5/thumbnails/28.jpg)
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](https://reader033.vdocuments.mx/reader033/viewer/2022050812/58998efc1a28ab30328b4a03/html5/thumbnails/29.jpg)
![Page 30: Node.js - Server Side Javascript](https://reader033.vdocuments.mx/reader033/viewer/2022050812/58998efc1a28ab30328b4a03/html5/thumbnails/30.jpg)
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](https://reader033.vdocuments.mx/reader033/viewer/2022050812/58998efc1a28ab30328b4a03/html5/thumbnails/31.jpg)
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](https://reader033.vdocuments.mx/reader033/viewer/2022050812/58998efc1a28ab30328b4a03/html5/thumbnails/32.jpg)
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](https://reader033.vdocuments.mx/reader033/viewer/2022050812/58998efc1a28ab30328b4a03/html5/thumbnails/33.jpg)
NPM - Using a package$ node secondscript.js
![Page 34: Node.js - Server Side Javascript](https://reader033.vdocuments.mx/reader033/viewer/2022050812/58998efc1a28ab30328b4a03/html5/thumbnails/34.jpg)
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](https://reader033.vdocuments.mx/reader033/viewer/2022050812/58998efc1a28ab30328b4a03/html5/thumbnails/35.jpg)
NPM - Dipendenze
![Page 36: Node.js - Server Side Javascript](https://reader033.vdocuments.mx/reader033/viewer/2022050812/58998efc1a28ab30328b4a03/html5/thumbnails/36.jpg)
![Page 37: Node.js - Server Side Javascript](https://reader033.vdocuments.mx/reader033/viewer/2022050812/58998efc1a28ab30328b4a03/html5/thumbnails/37.jpg)
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](https://reader033.vdocuments.mx/reader033/viewer/2022050812/58998efc1a28ab30328b4a03/html5/thumbnails/38.jpg)
Node - Create a Web Server
$ node server.js
![Page 39: Node.js - Server Side Javascript](https://reader033.vdocuments.mx/reader033/viewer/2022050812/58998efc1a28ab30328b4a03/html5/thumbnails/39.jpg)
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](https://reader033.vdocuments.mx/reader033/viewer/2022050812/58998efc1a28ab30328b4a03/html5/thumbnails/40.jpg)
Node.js - Development• Callback Hell, numerose funzioni vengono eseguite
al termine di un’altra. In successione.
![Page 42: Node.js - Server Side Javascript](https://reader033.vdocuments.mx/reader033/viewer/2022050812/58998efc1a28ab30328b4a03/html5/thumbnails/42.jpg)
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](https://reader033.vdocuments.mx/reader033/viewer/2022050812/58998efc1a28ab30328b4a03/html5/thumbnails/43.jpg)
Node.js - Development• express.js, Hello world!
![Page 44: Node.js - Server Side Javascript](https://reader033.vdocuments.mx/reader033/viewer/2022050812/58998efc1a28ab30328b4a03/html5/thumbnails/44.jpg)
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](https://reader033.vdocuments.mx/reader033/viewer/2022050812/58998efc1a28ab30328b4a03/html5/thumbnails/45.jpg)
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](https://reader033.vdocuments.mx/reader033/viewer/2022050812/58998efc1a28ab30328b4a03/html5/thumbnails/46.jpg)
Locomotive.js - MVC
Image from: https://smist08.wordpress.com/
![Page 47: Node.js - Server Side Javascript](https://reader033.vdocuments.mx/reader033/viewer/2022050812/58998efc1a28ab30328b4a03/html5/thumbnails/47.jpg)
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](https://reader033.vdocuments.mx/reader033/viewer/2022050812/58998efc1a28ab30328b4a03/html5/thumbnails/48.jpg)
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](https://reader033.vdocuments.mx/reader033/viewer/2022050812/58998efc1a28ab30328b4a03/html5/thumbnails/49.jpg)
Locomotive.js - server.js
![Page 50: Node.js - Server Side Javascript](https://reader033.vdocuments.mx/reader033/viewer/2022050812/58998efc1a28ab30328b4a03/html5/thumbnails/50.jpg)
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](https://reader033.vdocuments.mx/reader033/viewer/2022050812/58998efc1a28ab30328b4a03/html5/thumbnails/51.jpg)
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](https://reader033.vdocuments.mx/reader033/viewer/2022050812/58998efc1a28ab30328b4a03/html5/thumbnails/52.jpg)
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](https://reader033.vdocuments.mx/reader033/viewer/2022050812/58998efc1a28ab30328b4a03/html5/thumbnails/53.jpg)
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](https://reader033.vdocuments.mx/reader033/viewer/2022050812/58998efc1a28ab30328b4a03/html5/thumbnails/54.jpg)
Node.js - Production
• Normalmente i demoni muoiono se vanno in errore -> bisogna trovare un meccanismo per riavviarli
![Page 55: Node.js - Server Side Javascript](https://reader033.vdocuments.mx/reader033/viewer/2022050812/58998efc1a28ab30328b4a03/html5/thumbnails/55.jpg)
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](https://reader033.vdocuments.mx/reader033/viewer/2022050812/58998efc1a28ab30328b4a03/html5/thumbnails/56.jpg)
Node.js - ProductionPossiamo lanciare in automatica n demoni, dove n è il numero di core del sistema
![Page 57: Node.js - Server Side Javascript](https://reader033.vdocuments.mx/reader033/viewer/2022050812/58998efc1a28ab30328b4a03/html5/thumbnails/57.jpg)
Node.js - Production
Possiamo leggere i log in tempo reale
![Page 58: Node.js - Server Side Javascript](https://reader033.vdocuments.mx/reader033/viewer/2022050812/58998efc1a28ab30328b4a03/html5/thumbnails/58.jpg)
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://reader033.vdocuments.mx/reader033/viewer/2022050812/58998efc1a28ab30328b4a03/html5/thumbnails/59.jpg)
https://goo.gl/G9mHkoSample Project Repository on Github
![Page 60: Node.js - Server Side Javascript](https://reader033.vdocuments.mx/reader033/viewer/2022050812/58998efc1a28ab30328b4a03/html5/thumbnails/60.jpg)
Conclusioni
Popular Sites using Node.js
• Flickr.com • Groupon.com • Coursera.org • Linkedin.com • …. • ….
![Page 61: Node.js - Server Side Javascript](https://reader033.vdocuments.mx/reader033/viewer/2022050812/58998efc1a28ab30328b4a03/html5/thumbnails/61.jpg)
Grazie per l’attenzione