SlideShare une entreprise Scribd logo
1  sur  19
Télécharger pour lire hors ligne
MedTech
Dr. Lilia SFAXI
www.liliasfaxi.wix.com/liliasfaxi
Chp7- Server-Side JavaScript with NodeJS
NodeJS, ExpressJS
1
MedTech – Mediterranean Institute of Technology
CS-Web and Mobile Development
MedTech
MedTech
Server-Side Development
• Developing rich web sites and applications can be difficult to develop,
maintain and expand
• Problem: Schism between client and server components
• Client-side: HTML, CSS, JavaScript…
• Server-side: PHP, Java, .Net,…
• Data sent from server to client using XML, JSON, HTML-formatted text,…
• CommonJS Movement
• Goal: Eliminate gap between client and server
• Client-side Web technologies are more familiar to the users
• Need for a web server to process the code
2
Server-Side JavaScript
MedTech
Benefits of Server-Side JS
• Alleviates development complexity
• The same code can validate data on both the client (for immediate user
feedback) and on the server (for security)
• Validations never get out of sync.
• The same code can prepare both the HTML DOM server side and modify it
client-side, when the user changes the data or it's refreshed from the
server.
• Using the same code on both the client and the server, developers have
fewer technologies to learn and stay on top of, and fewer parts of the
application or site to maintain.
3
Server-Side JavaScript
MedTech
Server Architectures (1)
• Thread-based Server Architectures
• Associates each incoming connection with a separate
thread
• Uses synchronous blocking I/O
• Common approach that is well supported by many
programming languages
• Leads to a straight forward programming model
• All tasks necessary for request handling can be coded sequentially
• Provides a simple mental abstraction by isolating
requests and hiding concurrency
• Real concurrency is achieved by employing multiple threads/
processes at the same time.
• Usually place a single dispatcher thread (sometimes also
called acceptor thread) in front of a pool of threads for
connection handling
4
Server-Side JavaScript
MedTech
Server Architectures (2)
• Event-based Server Architectures
• Maps a single thread to multiple connections
• Asynchronous non-blocking I/O
• New events are queued
• The thread executes an event loop:
• Dequeuing events from the queue
• Processing the event
• Taking the next event or waiting for new events to be pushed
• The work executed by a thread is very similar to that of a scheduler, multiplexing multiple
connections to a single flow of execution.
• They take advantage of the fact that servers spend most of their time waiting for I/O operations
• Reading a file from a hard drive, accessing an external web service or waiting for a file to finish being uploaded…
• Every I/O operation is asynchronous, meaning that the server can continue to process incoming requests while the I/
O operation is taking place.
• This allows the programmer to relax the synchronization requirements and not have to worry about concurrent
threads of execution changing the shared memory state.
5
Server-Side JavaScript
MedTech
NODE JS
6
Server-Side JavaScript with NodeJS
MedTech
NodeJS
• Event-driven, asynchronous non-blocking I/O server
• Thanks to closures, anonymous functions and callbacks, JS is ideal for
event-driven programming
• Closures: functions that inherit variables from their enclosing environment.
• When you pass a function callback as an argument to another function that
will do I/O, this callback function will be invoked later, and this function will —
almost magically — remember the context in which it was declared, along
with all the variables available in that context and any parent contexts.
• These particularities can be very beneficial to event-driven
asynchronous systems:
• You can do event-driven programming without having to maintain the state by
passing it around to functions.
7
NodeJS
MedTech
Modules in Node JS
• Node implements the CommonJS modules standard
• In this standard each module has its own context, separated from the other
modules
• Modules cannot pollute a global scope — because there is none — and cannot
interfere with other modules.
• In Node, modules are referenced either by file path or by name
• Referenced by name modules are either core modules (preinstalled with Node)
or third-party modules installed using NPM
• Each module exposes a public API that the programmer can use after
the module is imported into the current script
8
NodeJS
MedTech
Loading and Exporting Modules
• To load/import a module, you have to use the require function
var module = require('module_name');
• The requirefunction returns an object that represents the JavaScript API
exposed by the module.
• Depending on the module, that object can be any JavaScript value — a function, an object with
some properties that can be functions, an array, or any other type of JavaScript object.
• To export an object/function/variable from a module, use the
module.exports object
9
NodeJS
function Circle(x, y, r) {
function area() {
return Math.PI * Math.pow(r, 2);;
}
return {
area: area
};
}
module.exports = Circle;
function printA() {
console.log('A');
}
module.exports.printA = printA;
module.exports.pi = Math.PI;
// To use these exported objects
var myModule2 = require('./myModule2');
myModule2.printA(); // -> A
console.log(myModule2.pi); // -> 3.141..
MedTech
Event Emitter Pattern
• In Node many objects emit events: Called Event Emitters
• a TCP server can emit a “connect” event every time a new client connects
• a file stream can emit a “data” event every time a new chunk of data is read.
• Event emitters allow programmers to subscribe to events they are
interested in
• The programmer attaches a callback function that will be invoked every time a
relevant event in that event emitter occurs.
• You can create your own Event Emitters
• Usage of the EventEmitter Pseudo-class
10
NodeJS
MedTech
Event Emitter Pattern: CPS
• Asynchronous programming does not use function return values to
denote that a function is finished
• Instead it uses the Continuation-Passing Style (CPS)
• Style of programming in which control is passed explicitly in the form of a
continuation.
• A function written in continuation-passing style takes as an extra argument
an explicit “continuation,” that is, a function of one argument. When the CPS
function has computed its result value, it “returns” it by calling the
continuation function with this value as the argument.
11
NodeJS
MedTech
Event Emitter Pattern: CPS
• A function invokes a callback after the operation is complete so that
your program can continue
• A common pattern in Node when using CPS, is to pass an error object as
a first argument to the callback function
12
NodeJS
var fs = require('fs');
fs.readFile('/etc/passwd', function(err, fileContent)
{
if (err) {
throw err;
}
console.log('file content', fileContent.toString());
});
MedTech
Event Emitter Pattern
• The standard callback pattern works well when you want the client to
be notified when a function completes
• If several events take place during execution, use the Event Emitter
Pattern
• Two types of objects are involved: an event emitter and event listeners
• Event emitters always have a type, denoted by a string
• Usually lowercase words with no spaces
• Types of events cannot be inferred programmatically
• The API should document its event types conveniently
13
NodeJS
MedTech
Using an Event Emitter
• Adding an event listener to an event type
readStream.addListener(“data”, receiveData); // or…
readStream.on(“data”, receiveData);
• Attaching an event listener to an event type, that will be called at most
once
readStream.once("data", receiveData);
• Removing a specific event listener of a given event
readStream.removeListener("data", receiveData);
• Removing all event listeners of a given event
readStream.removeAllListeners("data");
14
NodeJS
function receiveData(data) {
console.log("got data from file read stream: %j", data);
}
MedTech
Creating an Event Emitter
• To create an event emitter, create a class that inherits from EventEmitter
• This class now can emit events
• And clients can listen to these events
15
NodeJS
util = require('util');
var EventEmitter = require('events').EventEmitter;
// Here is the MyClass constructor:
var MyClass = function() {
}
util.inherits(MyClass, EventEmitter);
MyClass.prototype.someMethod = function() {
this.emit("custom", "argument 1", "argument 2");
};
var myInstance = new MyClass();
myInstance.on('custom event', function(str1, str2) {
console.log('got a custom event with the str1 %s and
str2 %s!', str1, str2);
});
MedTech
AS A CONCLUSION…
16
Server-Side JavaScript with NodeJS
MedTech
When to use NodeJS?
• Some typical applications:
• Stream-based real-time services
• Web Chat applications
• Static file servers
• If you need high-level concurrency,
• If you need intensive I/O and are not worried about CPU cycles
• If you are a JavaScript lover
17
NodeJS
MedTech
When NOT to use NodeJS?
• When you are doing very heavy and CPU intensive calculations on
server-side
• Event-loops are CPU hungry
• It is no match to enterprise-level application frameworks like Spring
(Java), Django (Python), Symphony (PHP),…
• Applications written on such platforms are meant to be highly user interactive
and involve complex business logic.
18
NodeJS
MedTech
Dr. Lilia SFAXI
www.liliasfaxi.wix.com/liliasfaxi
References
19
• Books
• Pedro Teixeira, Professional Node.JS, John Wiley & Sons Inc, , 2013
• Thesis
• Benjamin Erb, Concurrent Programming for Scalable Web Architectures: http://
berb.github.io/diploma-thesis/original/, consulted on March 2017

Contenu connexe

Tendances (20)

Introduction to Spring Boot!
Introduction to Spring Boot!Introduction to Spring Boot!
Introduction to Spring Boot!
 
Spring boot Introduction
Spring boot IntroductionSpring boot Introduction
Spring boot Introduction
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
Spring Data JPA
Spring Data JPASpring Data JPA
Spring Data JPA
 
Web Development with Python and Django
Web Development with Python and DjangoWeb Development with Python and Django
Web Development with Python and Django
 
Spring Boot Tutorial
Spring Boot TutorialSpring Boot Tutorial
Spring Boot Tutorial
 
Spring boot jpa
Spring boot jpaSpring boot jpa
Spring boot jpa
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
Introduction to Spring Boot
Introduction to Spring BootIntroduction to Spring Boot
Introduction to Spring Boot
 
Advance Java Topics (J2EE)
Advance Java Topics (J2EE)Advance Java Topics (J2EE)
Advance Java Topics (J2EE)
 
RESTful API - Best Practices
RESTful API - Best PracticesRESTful API - Best Practices
RESTful API - Best Practices
 
Spring boot
Spring bootSpring boot
Spring boot
 
REST & RESTful Web Services
REST & RESTful Web ServicesREST & RESTful Web Services
REST & RESTful Web Services
 
Introduction to spring boot
Introduction to spring bootIntroduction to spring boot
Introduction to spring boot
 
Spring Boot in Action
Spring Boot in Action Spring Boot in Action
Spring Boot in Action
 
Php and MySQL
Php and MySQLPhp and MySQL
Php and MySQL
 
Spring data jpa
Spring data jpaSpring data jpa
Spring data jpa
 
Spring boot - an introduction
Spring boot - an introductionSpring boot - an introduction
Spring boot - an introduction
 
Jdbc Ppt
Jdbc PptJdbc Ppt
Jdbc Ppt
 
Intro to React
Intro to ReactIntro to React
Intro to React
 

En vedette

Mobile developement
Mobile developementMobile developement
Mobile developementLilia Sfaxi
 
BigData_TP3 : Spark
BigData_TP3 : SparkBigData_TP3 : Spark
BigData_TP3 : SparkLilia Sfaxi
 
Introduction au Web
Introduction au WebIntroduction au Web
Introduction au WebLilia Sfaxi
 
Client-side JavaScript
Client-side JavaScriptClient-side JavaScript
Client-side JavaScriptLilia Sfaxi
 
Javascript Design Patterns
Javascript Design PatternsJavascript Design Patterns
Javascript Design PatternsLilia Sfaxi
 
Techday Arrow Group: Hadoop & le Big Data
Techday Arrow Group: Hadoop & le Big DataTechday Arrow Group: Hadoop & le Big Data
Techday Arrow Group: Hadoop & le Big DataArrow Group
 
BigData_TP2: Design Patterns dans Hadoop
BigData_TP2: Design Patterns dans HadoopBigData_TP2: Design Patterns dans Hadoop
BigData_TP2: Design Patterns dans HadoopLilia Sfaxi
 
BigData_TP5 : Neo4J
BigData_TP5 : Neo4JBigData_TP5 : Neo4J
BigData_TP5 : Neo4JLilia Sfaxi
 
BigData_TP4 : Cassandra
BigData_TP4 : CassandraBigData_TP4 : Cassandra
BigData_TP4 : CassandraLilia Sfaxi
 
BigData_TP1: Initiation à Hadoop et Map-Reduce
BigData_TP1: Initiation à Hadoop et Map-ReduceBigData_TP1: Initiation à Hadoop et Map-Reduce
BigData_TP1: Initiation à Hadoop et Map-ReduceLilia Sfaxi
 
BigData_Chp4: NOSQL
BigData_Chp4: NOSQLBigData_Chp4: NOSQL
BigData_Chp4: NOSQLLilia Sfaxi
 
BigData_Chp3: Data Processing
BigData_Chp3: Data ProcessingBigData_Chp3: Data Processing
BigData_Chp3: Data ProcessingLilia Sfaxi
 
BigData_Chp5: Putting it all together
BigData_Chp5: Putting it all togetherBigData_Chp5: Putting it all together
BigData_Chp5: Putting it all togetherLilia Sfaxi
 
BigData_Chp2: Hadoop & Map-Reduce
BigData_Chp2: Hadoop & Map-ReduceBigData_Chp2: Hadoop & Map-Reduce
BigData_Chp2: Hadoop & Map-ReduceLilia Sfaxi
 
BigData_Chp1: Introduction à la Big Data
BigData_Chp1: Introduction à la Big DataBigData_Chp1: Introduction à la Big Data
BigData_Chp1: Introduction à la Big DataLilia Sfaxi
 

En vedette (20)

Mobile developement
Mobile developementMobile developement
Mobile developement
 
BigData_TP3 : Spark
BigData_TP3 : SparkBigData_TP3 : Spark
BigData_TP3 : Spark
 
These
TheseThese
These
 
Tp4 - PHP
Tp4 - PHPTp4 - PHP
Tp4 - PHP
 
Introduction au Web
Introduction au WebIntroduction au Web
Introduction au Web
 
Angular
AngularAngular
Angular
 
Testing Angular
Testing AngularTesting Angular
Testing Angular
 
Client-side JavaScript
Client-side JavaScriptClient-side JavaScript
Client-side JavaScript
 
Javascript Design Patterns
Javascript Design PatternsJavascript Design Patterns
Javascript Design Patterns
 
Core JavaScript
Core JavaScriptCore JavaScript
Core JavaScript
 
Techday Arrow Group: Hadoop & le Big Data
Techday Arrow Group: Hadoop & le Big DataTechday Arrow Group: Hadoop & le Big Data
Techday Arrow Group: Hadoop & le Big Data
 
BigData_TP2: Design Patterns dans Hadoop
BigData_TP2: Design Patterns dans HadoopBigData_TP2: Design Patterns dans Hadoop
BigData_TP2: Design Patterns dans Hadoop
 
BigData_TP5 : Neo4J
BigData_TP5 : Neo4JBigData_TP5 : Neo4J
BigData_TP5 : Neo4J
 
BigData_TP4 : Cassandra
BigData_TP4 : CassandraBigData_TP4 : Cassandra
BigData_TP4 : Cassandra
 
BigData_TP1: Initiation à Hadoop et Map-Reduce
BigData_TP1: Initiation à Hadoop et Map-ReduceBigData_TP1: Initiation à Hadoop et Map-Reduce
BigData_TP1: Initiation à Hadoop et Map-Reduce
 
BigData_Chp4: NOSQL
BigData_Chp4: NOSQLBigData_Chp4: NOSQL
BigData_Chp4: NOSQL
 
BigData_Chp3: Data Processing
BigData_Chp3: Data ProcessingBigData_Chp3: Data Processing
BigData_Chp3: Data Processing
 
BigData_Chp5: Putting it all together
BigData_Chp5: Putting it all togetherBigData_Chp5: Putting it all together
BigData_Chp5: Putting it all together
 
BigData_Chp2: Hadoop & Map-Reduce
BigData_Chp2: Hadoop & Map-ReduceBigData_Chp2: Hadoop & Map-Reduce
BigData_Chp2: Hadoop & Map-Reduce
 
BigData_Chp1: Introduction à la Big Data
BigData_Chp1: Introduction à la Big DataBigData_Chp1: Introduction à la Big Data
BigData_Chp1: Introduction à la Big Data
 

Similaire à Server-side JS with NodeJS

Tech io nodejs_20130531_v0.6
Tech io nodejs_20130531_v0.6Tech io nodejs_20130531_v0.6
Tech io nodejs_20130531_v0.6Ganesh Kondal
 
Introduction to Node JS.pdf
Introduction to Node JS.pdfIntroduction to Node JS.pdf
Introduction to Node JS.pdfBareen Shaikh
 
Fundamental of Node.JS - Internship Presentation - Week7
Fundamental of Node.JS - Internship Presentation - Week7Fundamental of Node.JS - Internship Presentation - Week7
Fundamental of Node.JS - Internship Presentation - Week7Devang Garach
 
The Meteor Framework
The Meteor FrameworkThe Meteor Framework
The Meteor FrameworkDamien Magoni
 
Basic Understanding and Implement of Node.js
Basic Understanding and Implement of Node.jsBasic Understanding and Implement of Node.js
Basic Understanding and Implement of Node.jsGary Yeh
 
Introduction to angular | Concepts and Environment setup
Introduction to angular | Concepts and Environment setupIntroduction to angular | Concepts and Environment setup
Introduction to angular | Concepts and Environment setupAnsley Rodrigues
 
Kalp Corporate Node JS Perfect Guide
Kalp Corporate Node JS Perfect GuideKalp Corporate Node JS Perfect Guide
Kalp Corporate Node JS Perfect GuideKalp Corporate
 
IBM Bluemix OpenWhisk: Serverless Conference 2016, London, UK: The Future of ...
IBM Bluemix OpenWhisk: Serverless Conference 2016, London, UK: The Future of ...IBM Bluemix OpenWhisk: Serverless Conference 2016, London, UK: The Future of ...
IBM Bluemix OpenWhisk: Serverless Conference 2016, London, UK: The Future of ...OpenWhisk
 
Introduction to node.js aka NodeJS
Introduction to node.js aka NodeJSIntroduction to node.js aka NodeJS
Introduction to node.js aka NodeJSJITENDRA KUMAR PATEL
 
Elements for an iOS Backend
Elements for an iOS BackendElements for an iOS Backend
Elements for an iOS BackendLaurent Cerveau
 
Building production-quality apps with Node.js
Building production-quality apps with Node.jsBuilding production-quality apps with Node.js
Building production-quality apps with Node.jsmattpardee
 
NodeJS guide for beginners
NodeJS guide for beginnersNodeJS guide for beginners
NodeJS guide for beginnersEnoch Joshua
 
.NET Core Apps: Design & Development
.NET Core Apps: Design & Development.NET Core Apps: Design & Development
.NET Core Apps: Design & DevelopmentGlobalLogic Ukraine
 
introduction to node.js
introduction to node.jsintroduction to node.js
introduction to node.jsorkaplan
 
Decomposing the Monolith using Microservices that don't give you pain
Decomposing the Monolith using Microservices that don't give you painDecomposing the Monolith using Microservices that don't give you pain
Decomposing the Monolith using Microservices that don't give you painDennis Doomen
 

Similaire à Server-side JS with NodeJS (20)

Tech io nodejs_20130531_v0.6
Tech io nodejs_20130531_v0.6Tech io nodejs_20130531_v0.6
Tech io nodejs_20130531_v0.6
 
Beginners Node.js
Beginners Node.jsBeginners Node.js
Beginners Node.js
 
Introduction to Node JS.pdf
Introduction to Node JS.pdfIntroduction to Node JS.pdf
Introduction to Node JS.pdf
 
Fundamental of Node.JS - Internship Presentation - Week7
Fundamental of Node.JS - Internship Presentation - Week7Fundamental of Node.JS - Internship Presentation - Week7
Fundamental of Node.JS - Internship Presentation - Week7
 
The Meteor Framework
The Meteor FrameworkThe Meteor Framework
The Meteor Framework
 
Basic Understanding and Implement of Node.js
Basic Understanding and Implement of Node.jsBasic Understanding and Implement of Node.js
Basic Understanding and Implement of Node.js
 
Node js internal
Node js internalNode js internal
Node js internal
 
Introduction to angular | Concepts and Environment setup
Introduction to angular | Concepts and Environment setupIntroduction to angular | Concepts and Environment setup
Introduction to angular | Concepts and Environment setup
 
Real time web
Real time webReal time web
Real time web
 
Kalp Corporate Node JS Perfect Guide
Kalp Corporate Node JS Perfect GuideKalp Corporate Node JS Perfect Guide
Kalp Corporate Node JS Perfect Guide
 
IBM Bluemix OpenWhisk: Serverless Conference 2016, London, UK: The Future of ...
IBM Bluemix OpenWhisk: Serverless Conference 2016, London, UK: The Future of ...IBM Bluemix OpenWhisk: Serverless Conference 2016, London, UK: The Future of ...
IBM Bluemix OpenWhisk: Serverless Conference 2016, London, UK: The Future of ...
 
Introduction to node.js aka NodeJS
Introduction to node.js aka NodeJSIntroduction to node.js aka NodeJS
Introduction to node.js aka NodeJS
 
Elements for an iOS Backend
Elements for an iOS BackendElements for an iOS Backend
Elements for an iOS Backend
 
Building production-quality apps with Node.js
Building production-quality apps with Node.jsBuilding production-quality apps with Node.js
Building production-quality apps with Node.js
 
Windows 8 Metro apps and the outside world
Windows 8 Metro apps and the outside worldWindows 8 Metro apps and the outside world
Windows 8 Metro apps and the outside world
 
NodeJS guide for beginners
NodeJS guide for beginnersNodeJS guide for beginners
NodeJS guide for beginners
 
.NET Core Apps: Design & Development
.NET Core Apps: Design & Development.NET Core Apps: Design & Development
.NET Core Apps: Design & Development
 
Node_basics.pptx
Node_basics.pptxNode_basics.pptx
Node_basics.pptx
 
introduction to node.js
introduction to node.jsintroduction to node.js
introduction to node.js
 
Decomposing the Monolith using Microservices that don't give you pain
Decomposing the Monolith using Microservices that don't give you painDecomposing the Monolith using Microservices that don't give you pain
Decomposing the Monolith using Microservices that don't give you pain
 

Plus de Lilia Sfaxi

chp1-Intro à l'urbanisation des SI.pdf
chp1-Intro à l'urbanisation des SI.pdfchp1-Intro à l'urbanisation des SI.pdf
chp1-Intro à l'urbanisation des SI.pdfLilia Sfaxi
 
Plan d'études_INSAT_2022_2023.pdf
Plan d'études_INSAT_2022_2023.pdfPlan d'études_INSAT_2022_2023.pdf
Plan d'études_INSAT_2022_2023.pdfLilia Sfaxi
 
Lab1-DB-Cassandra
Lab1-DB-CassandraLab1-DB-Cassandra
Lab1-DB-CassandraLilia Sfaxi
 
TP2-UML-Correction
TP2-UML-CorrectionTP2-UML-Correction
TP2-UML-CorrectionLilia Sfaxi
 
TP1-UML-Correction
TP1-UML-CorrectionTP1-UML-Correction
TP1-UML-CorrectionLilia Sfaxi
 
TP0-UML-Correction
TP0-UML-CorrectionTP0-UML-Correction
TP0-UML-CorrectionLilia Sfaxi
 
TD4-UML-Correction
TD4-UML-CorrectionTD4-UML-Correction
TD4-UML-CorrectionLilia Sfaxi
 
TD3-UML-Séquences
TD3-UML-SéquencesTD3-UML-Séquences
TD3-UML-SéquencesLilia Sfaxi
 
TD3-UML-Correction
TD3-UML-CorrectionTD3-UML-Correction
TD3-UML-CorrectionLilia Sfaxi
 
TD2 - UML - Correction
TD2 - UML - CorrectionTD2 - UML - Correction
TD2 - UML - CorrectionLilia Sfaxi
 
TD1-UML-correction
TD1-UML-correctionTD1-UML-correction
TD1-UML-correctionLilia Sfaxi
 
Android - Tp1 - installation et démarrage
Android - Tp1 -   installation et démarrageAndroid - Tp1 -   installation et démarrage
Android - Tp1 - installation et démarrageLilia Sfaxi
 
Android - Tp2 - Elements graphiques
Android - Tp2 - Elements graphiques Android - Tp2 - Elements graphiques
Android - Tp2 - Elements graphiques Lilia Sfaxi
 
Android - Tp3 - intents
Android - Tp3 -  intentsAndroid - Tp3 -  intents
Android - Tp3 - intentsLilia Sfaxi
 
Android - TPBonus - web services
Android - TPBonus - web servicesAndroid - TPBonus - web services
Android - TPBonus - web servicesLilia Sfaxi
 
Android - Tp4 - graphiques avancés
Android - Tp4 - graphiques avancésAndroid - Tp4 - graphiques avancés
Android - Tp4 - graphiques avancésLilia Sfaxi
 

Plus de Lilia Sfaxi (20)

chp1-Intro à l'urbanisation des SI.pdf
chp1-Intro à l'urbanisation des SI.pdfchp1-Intro à l'urbanisation des SI.pdf
chp1-Intro à l'urbanisation des SI.pdf
 
Plan d'études_INSAT_2022_2023.pdf
Plan d'études_INSAT_2022_2023.pdfPlan d'études_INSAT_2022_2023.pdf
Plan d'études_INSAT_2022_2023.pdf
 
Lab3-DB_Neo4j
Lab3-DB_Neo4jLab3-DB_Neo4j
Lab3-DB_Neo4j
 
Lab2-DB-Mongodb
Lab2-DB-MongodbLab2-DB-Mongodb
Lab2-DB-Mongodb
 
Lab1-DB-Cassandra
Lab1-DB-CassandraLab1-DB-Cassandra
Lab1-DB-Cassandra
 
TP2-UML-Correction
TP2-UML-CorrectionTP2-UML-Correction
TP2-UML-Correction
 
TP1-UML-Correction
TP1-UML-CorrectionTP1-UML-Correction
TP1-UML-Correction
 
TP0-UML-Correction
TP0-UML-CorrectionTP0-UML-Correction
TP0-UML-Correction
 
TD4-UML
TD4-UMLTD4-UML
TD4-UML
 
TD4-UML-Correction
TD4-UML-CorrectionTD4-UML-Correction
TD4-UML-Correction
 
TD3-UML-Séquences
TD3-UML-SéquencesTD3-UML-Séquences
TD3-UML-Séquences
 
TD3-UML-Correction
TD3-UML-CorrectionTD3-UML-Correction
TD3-UML-Correction
 
TD2 - UML - Correction
TD2 - UML - CorrectionTD2 - UML - Correction
TD2 - UML - Correction
 
TD1 - UML - DCU
TD1 - UML - DCUTD1 - UML - DCU
TD1 - UML - DCU
 
TD1-UML-correction
TD1-UML-correctionTD1-UML-correction
TD1-UML-correction
 
Android - Tp1 - installation et démarrage
Android - Tp1 -   installation et démarrageAndroid - Tp1 -   installation et démarrage
Android - Tp1 - installation et démarrage
 
Android - Tp2 - Elements graphiques
Android - Tp2 - Elements graphiques Android - Tp2 - Elements graphiques
Android - Tp2 - Elements graphiques
 
Android - Tp3 - intents
Android - Tp3 -  intentsAndroid - Tp3 -  intents
Android - Tp3 - intents
 
Android - TPBonus - web services
Android - TPBonus - web servicesAndroid - TPBonus - web services
Android - TPBonus - web services
 
Android - Tp4 - graphiques avancés
Android - Tp4 - graphiques avancésAndroid - Tp4 - graphiques avancés
Android - Tp4 - graphiques avancés
 

Dernier

Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 

Dernier (20)

Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 

Server-side JS with NodeJS

  • 1. MedTech Dr. Lilia SFAXI www.liliasfaxi.wix.com/liliasfaxi Chp7- Server-Side JavaScript with NodeJS NodeJS, ExpressJS 1 MedTech – Mediterranean Institute of Technology CS-Web and Mobile Development MedTech
  • 2. MedTech Server-Side Development • Developing rich web sites and applications can be difficult to develop, maintain and expand • Problem: Schism between client and server components • Client-side: HTML, CSS, JavaScript… • Server-side: PHP, Java, .Net,… • Data sent from server to client using XML, JSON, HTML-formatted text,… • CommonJS Movement • Goal: Eliminate gap between client and server • Client-side Web technologies are more familiar to the users • Need for a web server to process the code 2 Server-Side JavaScript
  • 3. MedTech Benefits of Server-Side JS • Alleviates development complexity • The same code can validate data on both the client (for immediate user feedback) and on the server (for security) • Validations never get out of sync. • The same code can prepare both the HTML DOM server side and modify it client-side, when the user changes the data or it's refreshed from the server. • Using the same code on both the client and the server, developers have fewer technologies to learn and stay on top of, and fewer parts of the application or site to maintain. 3 Server-Side JavaScript
  • 4. MedTech Server Architectures (1) • Thread-based Server Architectures • Associates each incoming connection with a separate thread • Uses synchronous blocking I/O • Common approach that is well supported by many programming languages • Leads to a straight forward programming model • All tasks necessary for request handling can be coded sequentially • Provides a simple mental abstraction by isolating requests and hiding concurrency • Real concurrency is achieved by employing multiple threads/ processes at the same time. • Usually place a single dispatcher thread (sometimes also called acceptor thread) in front of a pool of threads for connection handling 4 Server-Side JavaScript
  • 5. MedTech Server Architectures (2) • Event-based Server Architectures • Maps a single thread to multiple connections • Asynchronous non-blocking I/O • New events are queued • The thread executes an event loop: • Dequeuing events from the queue • Processing the event • Taking the next event or waiting for new events to be pushed • The work executed by a thread is very similar to that of a scheduler, multiplexing multiple connections to a single flow of execution. • They take advantage of the fact that servers spend most of their time waiting for I/O operations • Reading a file from a hard drive, accessing an external web service or waiting for a file to finish being uploaded… • Every I/O operation is asynchronous, meaning that the server can continue to process incoming requests while the I/ O operation is taking place. • This allows the programmer to relax the synchronization requirements and not have to worry about concurrent threads of execution changing the shared memory state. 5 Server-Side JavaScript
  • 7. MedTech NodeJS • Event-driven, asynchronous non-blocking I/O server • Thanks to closures, anonymous functions and callbacks, JS is ideal for event-driven programming • Closures: functions that inherit variables from their enclosing environment. • When you pass a function callback as an argument to another function that will do I/O, this callback function will be invoked later, and this function will — almost magically — remember the context in which it was declared, along with all the variables available in that context and any parent contexts. • These particularities can be very beneficial to event-driven asynchronous systems: • You can do event-driven programming without having to maintain the state by passing it around to functions. 7 NodeJS
  • 8. MedTech Modules in Node JS • Node implements the CommonJS modules standard • In this standard each module has its own context, separated from the other modules • Modules cannot pollute a global scope — because there is none — and cannot interfere with other modules. • In Node, modules are referenced either by file path or by name • Referenced by name modules are either core modules (preinstalled with Node) or third-party modules installed using NPM • Each module exposes a public API that the programmer can use after the module is imported into the current script 8 NodeJS
  • 9. MedTech Loading and Exporting Modules • To load/import a module, you have to use the require function var module = require('module_name'); • The requirefunction returns an object that represents the JavaScript API exposed by the module. • Depending on the module, that object can be any JavaScript value — a function, an object with some properties that can be functions, an array, or any other type of JavaScript object. • To export an object/function/variable from a module, use the module.exports object 9 NodeJS function Circle(x, y, r) { function area() { return Math.PI * Math.pow(r, 2);; } return { area: area }; } module.exports = Circle; function printA() { console.log('A'); } module.exports.printA = printA; module.exports.pi = Math.PI; // To use these exported objects var myModule2 = require('./myModule2'); myModule2.printA(); // -> A console.log(myModule2.pi); // -> 3.141..
  • 10. MedTech Event Emitter Pattern • In Node many objects emit events: Called Event Emitters • a TCP server can emit a “connect” event every time a new client connects • a file stream can emit a “data” event every time a new chunk of data is read. • Event emitters allow programmers to subscribe to events they are interested in • The programmer attaches a callback function that will be invoked every time a relevant event in that event emitter occurs. • You can create your own Event Emitters • Usage of the EventEmitter Pseudo-class 10 NodeJS
  • 11. MedTech Event Emitter Pattern: CPS • Asynchronous programming does not use function return values to denote that a function is finished • Instead it uses the Continuation-Passing Style (CPS) • Style of programming in which control is passed explicitly in the form of a continuation. • A function written in continuation-passing style takes as an extra argument an explicit “continuation,” that is, a function of one argument. When the CPS function has computed its result value, it “returns” it by calling the continuation function with this value as the argument. 11 NodeJS
  • 12. MedTech Event Emitter Pattern: CPS • A function invokes a callback after the operation is complete so that your program can continue • A common pattern in Node when using CPS, is to pass an error object as a first argument to the callback function 12 NodeJS var fs = require('fs'); fs.readFile('/etc/passwd', function(err, fileContent) { if (err) { throw err; } console.log('file content', fileContent.toString()); });
  • 13. MedTech Event Emitter Pattern • The standard callback pattern works well when you want the client to be notified when a function completes • If several events take place during execution, use the Event Emitter Pattern • Two types of objects are involved: an event emitter and event listeners • Event emitters always have a type, denoted by a string • Usually lowercase words with no spaces • Types of events cannot be inferred programmatically • The API should document its event types conveniently 13 NodeJS
  • 14. MedTech Using an Event Emitter • Adding an event listener to an event type readStream.addListener(“data”, receiveData); // or… readStream.on(“data”, receiveData); • Attaching an event listener to an event type, that will be called at most once readStream.once("data", receiveData); • Removing a specific event listener of a given event readStream.removeListener("data", receiveData); • Removing all event listeners of a given event readStream.removeAllListeners("data"); 14 NodeJS function receiveData(data) { console.log("got data from file read stream: %j", data); }
  • 15. MedTech Creating an Event Emitter • To create an event emitter, create a class that inherits from EventEmitter • This class now can emit events • And clients can listen to these events 15 NodeJS util = require('util'); var EventEmitter = require('events').EventEmitter; // Here is the MyClass constructor: var MyClass = function() { } util.inherits(MyClass, EventEmitter); MyClass.prototype.someMethod = function() { this.emit("custom", "argument 1", "argument 2"); }; var myInstance = new MyClass(); myInstance.on('custom event', function(str1, str2) { console.log('got a custom event with the str1 %s and str2 %s!', str1, str2); });
  • 17. MedTech When to use NodeJS? • Some typical applications: • Stream-based real-time services • Web Chat applications • Static file servers • If you need high-level concurrency, • If you need intensive I/O and are not worried about CPU cycles • If you are a JavaScript lover 17 NodeJS
  • 18. MedTech When NOT to use NodeJS? • When you are doing very heavy and CPU intensive calculations on server-side • Event-loops are CPU hungry • It is no match to enterprise-level application frameworks like Spring (Java), Django (Python), Symphony (PHP),… • Applications written on such platforms are meant to be highly user interactive and involve complex business logic. 18 NodeJS
  • 19. MedTech Dr. Lilia SFAXI www.liliasfaxi.wix.com/liliasfaxi References 19 • Books • Pedro Teixeira, Professional Node.JS, John Wiley & Sons Inc, , 2013 • Thesis • Benjamin Erb, Concurrent Programming for Scalable Web Architectures: http:// berb.github.io/diploma-thesis/original/, consulted on March 2017