The Promise of Node.js

Building Scalable Web Applications

Owen Rogers / @exortech

https://github.com/exortech/presentations

Hi!

Owen Rogers / @exortech

Product Lead @ Pulse Energy

Paul Teehan

Energy Analytics Developer @ Pulse Energy

Big Data

+

Web technology

+

Data analytics

+

Behavioural science

Energy utilities

Smart grid data

Make the world a better place

Platform for building scalable web applications

Javascript virtual machine

Core set of libraries

Server-side Javascript - WTF?

A brief history of Javascript (abridged)

1995: Invented by Brendan Eich

XMLHttpRequest

2004: Ajax becomes de facto

2006: Javascript gets respect

2008: Chrome launched - browser wars resume

2009: Node.js launched

2014

  • Javascript: programming language of the web
  • V8: one of the most heavily optimized, widely used VMs
  • Node.js: unprecedent growth, web-centric community

2014

Server-side Javascript - who cares?

Node.js: asynchronous, evented I/O

Event-driven architecture (SEDA)

Low CPU, high I/O

Thread-based architectures: scale later

Service-oriented architecture

Node.js: built from the ground up for asynchrony

Node.js event loop

Dealing with asynchrony

Callbacks

Callback example

							
fs.readFile(filename, [options], callback)
							
							
var callback = function (err, data) {}
							
						

Callback example

							
fs.readFile('/buildings.csv', function (err, data) {
  if (err) {
  	throw err;
  }
  console.log(data);
});
							
						

Callback results

							
var result = fs.readFile('/buildings.csv', function (err, data) {
  if (err) {
  	throw err;
  }
  return data;
});
console.log(result); // ????
							
						

Callback chaining

							
var loadBuildings = function (buildingType, cb) {
	fs.readFile('/buildings.csv', function (err, data) {
	  if (err) {
	  	cb(err);
	  }
	  processData(data, cb);
	});
}							
						

Callback hell

What's the alternative?

Promises

JQuery Promises

Promise example

							
loadBuildings(buildingType).then(function (buildingData) {
	return processData(buildingData);
}).fail(function (err) {
	return handleError(err);
});
							
						

EventEmitters

							
process.on('uncaughtException', function (err) {
	logger.error(err, 'Unhandled error');
	process.exit(1);
});

process.on('exit', function () {
	logger.info('Process is exiting');
});
							
						

More information

owen@pulseenergy.com | @exortech