building fast, modern web applications with node.js and coffeescript
DESCRIPTION
The slides for a talk I gave at the Bits & Bytes computer science talk series at the University of Minnesota Morris in October 2013. Video of the talk is available here: http://www.kaltura.com/tiny/4lg1e This presentation gives a brief overview of why and how many modern websites are built using Node.js and CoffeeScript. Using the plethora of libraries available for Node, I show how to quickly and easily develop a website with automatic server-client syncing which scales and can handle thousands of concurrent connections.TRANSCRIPT
Node.jsBuilding Fast, Modern Web 2.0 Applications
Joe Einertson
University of Minnesota, Morris
October 30, 2013
What is Node?CoffeeScriptNode Basics
Node in PracticeConclusion
Table of Contents
1 What is Node?
2 CoffeeScript
3 Node Basics
4 Node in Practice
5 Conclusion
Joe Einertson Node.js
What is Node?CoffeeScriptNode Basics
Node in PracticeConclusion
BackgroundThe Old WayThe New Way
What is Node?
1 What is Node?BackgroundThe Old WayThe New Way
Joe Einertson Node.js
What is Node?CoffeeScriptNode Basics
Node in PracticeConclusion
BackgroundThe Old WayThe New Way
What is Node.js?
Network application framework built on Google’s V8JavaScript engine
Released in 2009, now widely used (Yahoo, Microsoft, eBay,LinkedIn, etc.)
Designed for scalability and performance
Single-threaded concurrency model
Joe Einertson Node.js
What is Node?CoffeeScriptNode Basics
Node in PracticeConclusion
BackgroundThe Old WayThe New Way
The Old Way
Older model of server design:
One thread per client
2MB per thread
I/O either blocks, is manually async, or is async throughexternal library
Large set of tools/capabilities built in
Joe Einertson Node.js
What is Node?CoffeeScriptNode Basics
Node in PracticeConclusion
BackgroundThe Old WayThe New Way
The New Way
Node (and other newer frameworks like Akka, Vert.x, Tornado,etc.) use a different model:
One thread, total
Non-blocking, event-driven I/O
Event loop drives entire server
Barebones
Goal: 10,000 concurrent connections
Joe Einertson Node.js
What is Node?CoffeeScriptNode Basics
Node in PracticeConclusion
BackgroundThe Old WayThe New Way
Benefits of the New Way
Much less overhead per user
No concurrency = no concurrency bugs
Scaling is easy
Really fast
Joe Einertson Node.js
What is Node?CoffeeScriptNode Basics
Node in PracticeConclusion
BackgroundThe Old WayThe New Way
Benefits of Node
Some benefits are specific to Node:
Underlying engine is fast, mature and well-maintained
Same language on server and client (!)
Joe Einertson Node.js
What is Node?CoffeeScriptNode Basics
Node in PracticeConclusion
BackgroundThe Old WayThe New Way
CPU-intensive = I/O
So, how do we handle CPU-intensive work? Turn it into I/O!
Spin off new process
Yield control
Resume when computation finished
Result is asynchronous and efficient
Joe Einertson Node.js
What is Node?CoffeeScriptNode Basics
Node in PracticeConclusion
What is CoffeeScript?CoffeeScript in 10 Minutes
CoffeeScript
2 CoffeeScriptWhat is CoffeeScript?CoffeeScript in 10 Minutes
Joe Einertson Node.js
What is Node?CoffeeScriptNode Basics
Node in PracticeConclusion
What is CoffeeScript?CoffeeScript in 10 Minutes
What is CoffeeScript?
First released in 2009
Syntax inspired by Python
Transcompiles to easily readable JavaScript
Seeing wider adoption with popularity of Node.js
Joe Einertson Node.js
What is Node?CoffeeScriptNode Basics
Node in PracticeConclusion
What is CoffeeScript?CoffeeScript in 10 Minutes
CoffeeScript Basics
Example
# Variables aren’t typed or declared
x = 2 + 2
# Everything is an expression
height = if isMobile then 300 else 800
# As in JS, easily declare arrays and objects
arr = [1, 2, 3]
obj = {year: 2004, model: "Camry"}
Joe Einertson Node.js
What is Node?CoffeeScriptNode Basics
Node in PracticeConclusion
What is CoffeeScript?CoffeeScript in 10 Minutes
CoffeeScript Functions
Example
# Functions are declared with () ->
# Last value implicitly returned
square = (x) -> x * x
# Indentation is used instead of braces
area = (r) ->
if r <= 0
0
else
pi = 3.14
pi * r * r
Joe Einertson Node.js
What is Node?CoffeeScriptNode Basics
Node in PracticeConclusion
What is CoffeeScript?CoffeeScript in 10 Minutes
More CoffeeScript
Example
# Parentheses are optional in function calls
Math.pow(2, n) == Math.pow 2, n
# Useful for functional-style invocations
squares = util.map [1, 2, 3], (x) -> x * x
# String interpolation is awesome...
console.log "#{x} + #{y} = #{x+y}"
# ...especially when compared to vanilla JS strings
console.log "" + x + " + " + y + " = " + (x + y)
Joe Einertson Node.js
What is Node?CoffeeScriptNode Basics
Node in PracticeConclusion
What is CoffeeScript?CoffeeScript in 10 Minutes
Destructuring Assignment...?
Example
# Quickly assign multiple values
[quotient, remainder] = divide 7, 3
# Take apart and put together objects easily
{age, name} = dbResult
x = 3
point = {x, y: 4}
Joe Einertson Node.js
What is Node?CoffeeScriptNode Basics
Node in PracticeConclusion
What is CoffeeScript?CoffeeScript in 10 Minutes
Classes!
CoffeeScript has classes!
Example
class Point
# Automatically assign params to instance fields
constructor: (@x, @y) ->
@sum = x + y
difference: ->
@x - @y
p = new Point(4, 5)
x.difference() # -1
Joe Einertson Node.js
What is Node?CoffeeScriptNode Basics
Node in PracticeConclusion
Hello WorldBasic Web ServerShow me the I/O
Node Basics
3 Node BasicsHello WorldBasic Web ServerShow me the I/O
Joe Einertson Node.js
What is Node?CoffeeScriptNode Basics
Node in PracticeConclusion
Hello WorldBasic Web ServerShow me the I/O
Hello World
Example
net = require ’net’
net.createServer (stream) ->
stream.write ’Hello World!\r\n’
stream.pipe stream
.listen(8000)
Joe Einertson Node.js
What is Node?CoffeeScriptNode Basics
Node in PracticeConclusion
Hello WorldBasic Web ServerShow me the I/O
Hello World
Example
http = require ’http’
http.createServer (request, response) ->
# 200 = HTTP ’everything OK’ status
response.writeHead 200,
{’Content-Type’: ’text/plain’}
response.end ’Hello World!’
.listen(8000)
Response time: <1 ms
Apache response time: 100 ms
Joe Einertson Node.js
What is Node?CoffeeScriptNode Basics
Node in PracticeConclusion
Hello WorldBasic Web ServerShow me the I/O
Asynchronous I/O
Example
http = require ’http’
db = require ’./server/db.coffee’
http.createServer (request, response) ->
query = ’SELECT * FROM STOCK;’
db.request query, (err, stock) ->
return sendError response, 500 if err
response.writeHead 200, { ... }
response.end stock.toString()
.listen(8000)
Joe Einertson Node.js
What is Node?CoffeeScriptNode Basics
Node in PracticeConclusion
LibrariesexpressSocket.IOBackboneswig
Node in Practice
4 Node in PracticeLibrariesexpressSocket.IOBackboneswig
Joe Einertson Node.js
What is Node?CoffeeScriptNode Basics
Node in PracticeConclusion
LibrariesexpressSocket.IOBackboneswig
Libraries
Web server framework: express
Async control flow: async
Client-server sync + MVC: Backbone
”Push” framework: Socket.IO
Client library: jQuery/Prototype
Templates: swig/Mustache/Hogan
Utilities: Underscore
Libraries and dependencies handled with Node Package Manager(npm)
Joe Einertson Node.js
What is Node?CoffeeScriptNode Basics
Node in PracticeConclusion
LibrariesexpressSocket.IOBackboneswig
express
express is a widely used wrapper over the built-in Node HTTPlibrary.
Example
express = require ’express’
app = express()
app.get ’/news/:slug’, (req, res) ->
res.send "You want the news about #{req.slug}!"
app.get ’/*’, (req, res) ->
res.sendfile ’index.html’
app.listen(8000)
Joe Einertson Node.js
What is Node?CoffeeScriptNode Basics
Node in PracticeConclusion
LibrariesexpressSocket.IOBackboneswig
Socket.IO
Socket.IO provides a ”push” framework - essentially, a pipebetween server and client.
Example (Server)
socketIO = require ’socket.io’
io = socketIO.listen(app)
io.on ’connection’, (socket) ->
ClientManager.add socket
socket.on ’getData’, (username) ->
socket.emit ’data’, cache.findPerson(username)
Joe Einertson Node.js
What is Node?CoffeeScriptNode Basics
Node in PracticeConclusion
LibrariesexpressSocket.IOBackboneswig
Socket.IO
Example (Client)
socket = io.connect ’http://localhost’
socket.emit ’getData’, auth.getUsername()
socket.on ’data’, (personData) ->
...
Joe Einertson Node.js
What is Node?CoffeeScriptNode Basics
Node in PracticeConclusion
LibrariesexpressSocket.IOBackboneswig
Backbone
Backbone provides the client a MVC model as well as automaticclient-server syncing.
Example (Models)
class Message extends Backbone.Model
initialize: ->
@on ’change:message’, ’addEditMsg’
addEditMsg: ->
newMsg = "#{ @get ’message’ } (Edited)"
# Use silent: true to prevent infinite loop
@set {message: newMsg}, {silent: true}
Joe Einertson Node.js
What is Node?CoffeeScriptNode Basics
Node in PracticeConclusion
LibrariesexpressSocket.IOBackboneswig
Backbone
Example (Views)
class MessageView extends Backbone.View
tagName: ’div’
className: ’message’
template: ’message’
events:
’click .name’: ’showMsgAuthor’
initialize: ->
@listenTo @model, ’change’, @render
Joe Einertson Node.js
What is Node?CoffeeScriptNode Basics
Node in PracticeConclusion
LibrariesexpressSocket.IOBackboneswig
Backbone
Example (Views)
class MessageView extends Backbone.View
# Even complex rendering is easy with Backbone
render: ->
data =
time: @get(’time’).toLocaleString()
color:
if @get(‘byAdmin’)
’red’
else
’white’
super(data)
Joe Einertson Node.js
What is Node?CoffeeScriptNode Basics
Node in PracticeConclusion
LibrariesexpressSocket.IOBackboneswig
Backbone
Example (All Together Now)
# Make a model...
model = new Message(data)
# ...make a view for that model...
view = new MessageView({ model })
# ...and insert it into the document
$(’.messages’).append view.render().el
Joe Einertson Node.js
What is Node?CoffeeScriptNode Basics
Node in PracticeConclusion
LibrariesexpressSocket.IOBackboneswig
Templates with Swig
Building views with templates is easy.
Example (message.html)
From: {{ name }}<br />
Date: {{ time }}<br />
{{ message }}
Example (Client or Server)
msgTemplate = swig.compile rawTemplate
msg = msgTemplate(msgData)
$(’body’).append msg # Client only
Joe Einertson Node.js
What is Node?CoffeeScriptNode Basics
Node in PracticeConclusion
Webapp DemoTying It All TogetherMore ResourcesQuestions
Conclusion
5 ConclusionWebapp DemoTying It All TogetherMore ResourcesQuestions
Joe Einertson Node.js
What is Node?CoffeeScriptNode Basics
Node in PracticeConclusion
Webapp DemoTying It All TogetherMore ResourcesQuestions
App Demo
Simple webchat app
Multi-user chat
Changes propagate between server and all clients
Very little implementation logic
99% business logic
Joe Einertson Node.js
What is Node?CoffeeScriptNode Basics
Node in PracticeConclusion
Webapp DemoTying It All TogetherMore ResourcesQuestions
How Big?
Server: 200 lines
Client: 100 lines
HTML: 40 lines
CSS: 30 lines
Joe Einertson Node.js
What is Node?CoffeeScriptNode Basics
Node in PracticeConclusion
Webapp DemoTying It All TogetherMore ResourcesQuestions
Why Node?
Runs fast
Codes fast
Scales
Cross-platform
Huge library ecosystem
Joe Einertson Node.js
What is Node?CoffeeScriptNode Basics
Node in PracticeConclusion
Webapp DemoTying It All TogetherMore ResourcesQuestions
Why CoffeeScript?
Compatible with JS
Cleans up JS syntax
About 30% shorter than equivalent JS code
Joe Einertson Node.js
What is Node?CoffeeScriptNode Basics
Node in PracticeConclusion
Webapp DemoTying It All TogetherMore ResourcesQuestions
More Resources
Node’s own ”why?”: http://nodejs.org/about
The C10K problem: http://www.kegel.com/c10k.html
My app’s code:https://github.com/royaldark/node-chat-demo
Everything Node, by popularity: http://www.nodecloud.org
Joe Einertson Node.js
What is Node?CoffeeScriptNode Basics
Node in PracticeConclusion
Webapp DemoTying It All TogetherMore ResourcesQuestions
Questions
Any questions?
Joe Einertson Node.js