node.js
Benjamin Erb, Michael Müller | 2012-02-13
Single-threaded and event-driven
JavaScript outside your browser
Michael Müller
Student @ Ulm University
Computer Science and Media
Interests:
unix, web technologies, creative coding, ubiquitous computing
Contact:
Benjamin Erb
Student @ Ulm University
Computer Science and Media
Interests:
web technologies, scalable architectures, distributed systems and mobile/ubiquitous computing
Contact:
IOException.de
selected nerd stuff by CS students @uulm
UlmAPI.de
datalove ♥ – a local group of open data enthusiasts
Array.prototype.inArray = function(value) { for (var index in this) { /* ... */ } } [1,2,4].inArray(3); delete song.artist hasOwnProperty();
var song = { "never": "gonna", "give" : "you", "up": { "never": 2, "gonna": true, "let" : [2, 4, 6], "you" : function() { return 1; }, "down" : null } }
Functions as first-class citizens
var callback = function(result) { //... }; doItAsynchronously(foo, bar, callback);
JavaScript intrinsically supports event-oriented programming!
Anonymous functions
setTimeout( function() { /* ... */ }, 1000);
Functions as variables
var foo = function() {} foo(); execute(foo);
Closures
var foo = function() { var value = 42; return { getValue: function() { return this.value } } } var obj = foo();
Cascading
getBox() .setPosition(30, 40) .setBorder(1) .setVisible(true)
// Objects { foo: "bar", year: 2012 } // Arrays [ "a", "b", "c" ] // Strings "john doe" // Numbers 42 2e+6 2.34 // Boolean true // Null null
{ "Some": "String", "Large": 2e+6, "Small": 42, "An Object": { "An Array": [ "Un", "Dos", "Tres" ], "Empty Array": [], "Nothing": null } }
// Object as a JSON-String JSON.stringify( {two: 2, three: 3} );
// String as a JSON-Objekt var foo = '{"one":1, "two":"2"}'; var bar = JSON.parse(foo);
To provide a purely evented, non-blocking infrastructure to script highly concurrent programs.
Well, in node everything runs in parallel, except your code.
http-parser
)epoll
, kqueue
, /dev/poll
or select
SQL Query with Java
Statement s = conn.createStatement(); s.executeQuery("SELECT id FROM users"); ResultSet rs = s.getResultSet(); // use result set
Pseudo example in asynchronous JavaScript
db.executeStatement("SELECT id FROM users", function(resultSet) { // use result }); //...
var fs = require('fs'); //Async... var callback = function(err, stats){ console.log(stats); }; fs.stat("/etc/passwd", callback);
var fs = require('fs'); //Sync: Don't try this at home... var stats = fs.statSync("/etc/passwd"); console.log(stats);
RAM Access | 250 Cycles |
Harddisk I/O | 41.000.000 Cycles |
Network I/O | 240.000.000 Cycles |
Well, in node everything runs in parallel, except your code.
var net = require('net'); var server = net.createServer(function (socket) { socket.write("Echo server\r\n"); socket.pipe(socket); }); server.listen(1337, "127.0.0.1");
// config.js exports.port = 1337;
// echo-server.js var config = require('./config.js') server.listen(config.port, 'localhost');
process
, cluster
, child_process
Socket.IO aims to make realtime apps possible in every browser and mobile device […]
// Server var io = require('socket.io').listen(80); io.sockets.on('connection', function (socket) { socket.emit('news', { hello: 'world' }); socket.on('my other event', function (data) { console.log(data); }); });
// Client <script src="/socket.io/socket.io.js"></script> <script> var socket = io.connect('http://localhost'); socket.on('news', function (data) { console.log(data); socket.emit('my other event', { my: 'data' }); }); </script>
Request is designed to be the simplest way possible to make http calls. It support HTTPS and follows redirects by default.
var options = { url: 'http://foo/login', form: {'email': 'john@doe.de', 'password' : 'mypw'} }; request.post(options, function (err, res, body) { request.get('http://foo/orders', function (err, resp, body) { //... }); });
var jsdom = require('jsdom'); jsdom.env({ html: 'http://reddit.com/', scripts: ['http://code.jquery.com/jquery-1.7.1.min.js'], done: function(errors, window) { // ? } });
var jsdom = require('jsdom'); jsdom.env({ html : 'http://reddit.com/', scripts : ['http://code.jquery.com/jquery-1.7.1.min.js'], done: function(errors, window) { var cnt = 0; window.$("a.title").each(function() { if (cnt++ < 3) console.log(window.$(this).text()); }); } });
pcap_session.on('packet', function (raw_packet) { var packet = pcap.decode.packet(raw_packet); console.log(packet.link.ip.tcp.dport); });
tcp_tracker.on('start', function() {}); tcp_tracker.on('end', function() {});
doA(foo, function (err, a) { doB(bar, function (err, b) { doC(bla, function (err, c) { doD(4, function (err, d) { doE(d, function (err, e) { doF(e++, function (err, f) { //THIS IS SPA…GHETTI! }); }); }); }); }); });
function id(x) { return x; }
function id(x,cp) { cp(x); }
Chain the calls, pass a final "continuated" callback for completition:
fn2( fn1( 123 )) //regular chaining fn1(123, fn2) //CPS style
async.waterfall([ function(callback){ callback(null, 'one', 'two'); }, function(arg1, arg2, callback){ callback(null, 'three'); }, function(arg1, callback){ // arg1 now equals 'three' callback(null, 'done'); } ], function (err, result) { // result now equals 'done' });
Douglas Crockford
JavaScript: The Good Parts
2008, O'Reilly Media, 170 pages
ISBN: 978-0-596-51774-8
David Flanagan
JavaScript: The Definitive Guide
2011, O'Reilly Media, 1098 pages
ISBN: 978-0-596-80552-4
Slide deck: github.com/berb/html5slides-uulm
This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License.
Title photo: Michael Müller, cc-by 3.0