CV.js, June 19 2013
Michael Holroyd
node.js
server-side event-driven javascript
express
a minimialist web-framework for node.js
mongodb
a schemaless document database
This simple web server written in node responds with "Hello World" for every request.
1 var http = require('http');
2 http.createServer(function (req, res) {
3 res.writeHead(200, {'Content-Type': 'text/plain'});
4 res.end('Hello World\n');
5 }).listen(1337, '127.0.0.1');
1 var express = require('express');
2 var app = express();
3 app.get('/', function(req, res){
4 res.send('Hello World');
5 });
6 app.listen(1337);
var allowCrossDomain = function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With');
// intercept OPTIONS method
if ('OPTIONS' === req.method) { res.send(200); }
else { next(); }
};
app.configure(function(){
app.use(express.logger());
app.use(allowCrossDomain);
});
var mongo = require('mongodb');
mongo.connect(mongoUri,{auto_reconnect:true},function(err, db){ app.get('/firehose', function(req, response) { db.collection('twists', function(err, twists) { twists.find({}).sort({"created_at":-1}).toArray(function(err, twistArray) { response.send(twistArray); }); }); }); }
var r = db.twists.aggregate({ $group: { _id: "$identifier", twistsPerDevice: { $sum: 1 }, twhandle: { $max: "$twhandle" } } });
r.result.map(function(o){ if (o.twhandle) { db.twists.update( { identifier: o._id }, { twhandle: o.twhandle } ); } });
var view = {
title: "Joe",
calc: function () {
return 2 + 4;
}
};
var output = mustache.render("{{title}} spends {{calc}}", view);
var mustacheTwist = mustache.compile(fs.readFileSync("twist.html",'utf8'));
app.get('/:id', function(req, response) {
db.collection('twists', function(err, twists) {
var c = twists.find({_id: req.params.id});
c.nextObject(function(err,twist){
var view = {
server: "focustwist.com",
twist_id: req.params.id,
created_at: moment(twist.created_at).fromNow(),
twhandle: twist.twhandle,
};
response.send(mustacheTwist(view));
});
});
});
app.configure(function(){
app.use(express.logger());
app.use(express.bodyParser());
app.use(allowCrossDomain);
app.use(express.static(__dirname + "/public"));
});
~1,200 simultaneous users
~500 hits per second
(read-heavy workload)