Learn You The Node.js
For Much Win
What is Node.js?
A simple platform for writing
… network-centric
… JavaScript applications
… using event-driven, non-blocking I/O
For writing applications
Target platforms:
- OSX
- Linux
- Solaris
- Windows
Also: *BSD, Linux variants & ARM: Raspberry Pi, BeagleBone, Kindle, webOS
And Browserify
JavaScript
V8 (Chrome)
Single runtime target
Many familiar extras:
console.log() // info, warn, error, dir,
// time, timeEnd, trace, assert
setTimeout() // setInterval, setImmediate
JSON // of course
Network-centric
Node core:
- ¼ platform
- ¼ dev support
- ¼ abstractions, OS, libs & filesystem
- ¼ networking
TCP, UDP, HTTP, HTTPS, TLS, SSL, URLs, query strings
Event-driven, non-blocking I/O
Reactionary: callbacks & events everywhere. Call Me Maybe.
First-class functions FTW!
// callbacks
fs.readFile('data.txt', 'utf8', function (err, data) {
var lines = data.split('\n').length
console.log(lines + ' lines')
})
// events
server.on('connection', function (stream) {
console.log('someone connected!')
})
Event-driven, non-blocking I/O
Scalability: kernel-level non-blocking socket I/O:epoll
or select
Concurrent: worker threads for file I/O
JavaScript thread only needs to block for JavaScript!
Unless you tell it otherwise
Event-driven, non-blocking I/O
// Synchronous (avoid this)
console.log('Reading file...')
var data = fs.readFileSync('data.txt', 'utf8')
var lines = data.split('\n').length
console.log(lines + ' lines')
// Asynchronous (embrace this)
fs.readFile('data.txt', 'utf8', function (err, data) {
var lines = data.split('\n').length
console.log(lines + ' lines')
})
console.log('Reading file...')
JavaScript | Node core library | ||||
C / C++ | Node bindings | ||||
V8 | libuv |
OpenSSL zlib http_parser cares |
Original version of this table by Bert Belder: http://www.youtube.com/watch?v=nGn60vDSxQ4
libuv and the event loop
JavaScript callbacks | ||
Timers | Sleep? | |
Socket I/O | Filesystem I/O | OS events |
GIF analogy credit: http://nodejsreactions.tumblr.com/post/56979518608/the-node-js-event-loop
npm - the Node Package Manager
Makes publishing and using packages a breeze
Minimises dependency and version conflicts
Ease and simplicity of reuse has encouraged a culture of extreme modularity
Packages per day across popular platforms (source: www.modulecounts.com)
Chart credit: http://blog.nodejitsu.com/npm-innovation-through-modularity
var net = require('net')
var sockets = {}
var server = net.createServer(function (socket) {
var id = socket.remoteAddress + ':' + socket.remotePort
sockets[id] = socket
socket.on('end', function () { delete sockets[id] })
socket.on('data', function (data) {
msg('<' + id + '> ' + data)
})
msg('* ' + id + ' joined the chat')
})
function msg (msg) {
Object.keys(sockets).forEach(function (p) {
try { sockets[p].write(msg.replace(/(\r?\n)+/g, '') + '\n') } catch (e) {}
})
}
server.listen(1337)