All aboard theNode.JSExpress#SotR14
You know Node?Kev McCabe is covering TDD
SotR14 - Mura Room
Who is this guy?David Boyer
Senior SoftwareDeveloper
NHS Wales InformaticsService
...and yes... that'sme in the mask @
SotR13
Node.jsA JavaScript runtime
http://nodejs.org
The DetailsJavaScriptGoogle's V8 engineOpen Source - MIT LicenseCross platformSingle threaded codeMulti threaded IO
What can it do?Build web applications
Creating command line toolsCreate desktop applications
(node-webkit)
Who is using it?PayPal, LinkedIn, Yahoo, Microsoft,
eBay, 37signals, LearnBoost,Yammer, Walmart
Node in detail
In the beginning...Install
Command line
Action!*nodeconsole.log('Hello Scotch');
Using the APIvar fs = require('fs'); // Filesystem APIvar http = require('http'); // http APIvar crypto = require('crypto'); // Crypto API
One thread to rulethem all!
One thread for JavaScriptMultiple threads for I/O
The Event LoopEventQueue
Single js thread MultipleI/OThreads
What does the code looklike?
var fs = require('fs');var rawData = fs.readFileSync('sotr.json');var data = JSON.parse(rawData);console.log(new Date());console.log(data.message);
Why not just be multi-threaded?
Each thread needs morememory
Switching between threadscosts CPU
Avoids thread safety issues
Scaling single threadsThe Cluster API
↗ ⇶ →
↘
var cluster = require('cluster');var http = require('http');var cpus = require('os').cpus().length;
if (cluster.isMaster) { for (var i = 0; i < cpus; i++) { cluster.fork(); } cluster.on('exit', function(worker, code, signal) console.log('Process ID ' + worker.process.pid + });} else { http.createServer(function(req, res) {...}).listen(}
Switching mindsetFrom sync to async
Lots of callbacksCallback Hell!
Highway to Hellfs.readFile('sotr.json', function(err, data) { var info = JSON.parse(data); db.findOne({id: info.id}, function(err, record) fs.writeFile('sotr.dat', record.title, function console.log('Finish job'); }) })})
Escape from NestedCallbacksBreak it apart
Use a async module like"async"
PromisesGenerators (ES6)
Node as a webapplication
var http = require('http');
var server = http.createServer(function(req, res) res.end('Hello Scotch!');});
server.listen(80);
Modules// conf.jsfunction Conference(name, year) { this.name = name; this.year = year;};Conference.prototype.getTitle = function() { return this.name + ' ' + this.year;};module.exports = Conference
// index.jsvar Conf = require(__dirname + '/conf.js');var sotr = new Conf('Scotch on the Rocks', 2014);console.log(sotr.getTitle());
npmThe Node.js Package Manager
Initialise yourproject
npm init
name: (conference) sotr-exampleversion: (0.0.0) 0.1.2description: An example projectentry point: (index.js) index.jstest command: grunt nodeunitgit repository: git://github.com/misterdai/isnota.git#masterkeywords: example, appauthor: David Boyerlicense: (BSD-2-Clause) MIT
Finding moduleshttps://npmjs.org
https://nodejsmodules.org/http://eirikb.github.io/nipster/
Common modulesDatabases: mysql, mongodb,
sqliteCallbacks: async, q, when, co
Testing: Mocha, nodeunit,should
Templating: Jade, handlebars,ejs
Web frameworks: express,geddy, sails
Installing modulesnpm install asyncnpm install --save coffee-scriptnpm install --save-dev grunt-imagemin
npm install
npm uninstall --save coffee-script
Installing commandsnpm install -g coffee-scriptnpm uninstall -g grunt-clinpm install -g gulp
Other npm superpowers
Publish modulesExecute scripts (e.g. npm build,
npm run)Bump your version number
(semver)
SummaryLet npm manage your modules
Use it to install useful toolssuch as grunt
Don't have to keepnode_modules in source
controlStore project related
commands in package.json
Express yourselfExpress, a web framework for
Node.jsVery flexible
Minimal
Version 4Bundled middleware are nowtheir own modules*.* Except "static".More robust routing.app.router() is gone andmore flexible methods are nowavailable.
Installingmkdir websitecd websitenpm initnpm install --save expresstouch index.js
A static siteServing static files from a
directory
A dynamic siteJavaScript providing the content
A template enginehttps://github.com/visionmedia/consolidate.jsJade, EJS (Embedded JavaScript),
Handlebars...
Try being MEAN!
Popular stack for building Node.jsbased web apps.
MongoDBE xpressA ngularJSN ode.js
Thanks forlistening to my
first everconference talk
Questions
If we have time...
...or catch me at the bar .
GAME OVERAll aboard the
NodeJS ExpressDavid "Mister Dai"
Boyer @misterdai
Top Related