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