public
Last active

using node to display realtime heatmap of user's clicks

  • Download Gist
server.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107
var sys = require('sys'),
fs = require('fs'),
Url = require('url'),
http = require('http'),
querystring = require('querystring');
 
//create a Heatmap Obj that inherits
//from EventEmitter
var events = require('events');
function Heatmap() {
events.EventEmitter.call(this);
};
Heatmap.super_ = events.EventEmitter;
Heatmap.prototype = Object.create(events.EventEmitter.prototype, {
constructor: {
value: Heatmap,
enumerable: false
}
});
 
//save dataPoint and emit event 'added'
//that is listened to by displayNewDataPoints
Heatmap.prototype.add = function(xyPoints) {
var self = this;
self.xyPoints = xyPoints;
fs.open("./clickcount.txt", "a", 0666, function(er, fd){
var timeStamp = Math.round(new Date().getTime() / 1000);
fs.write(fd, xyPoints.x+','+xyPoints.y+";\n", null);
console.log('displaying new points. x: '+xyPoints.x + ' y:'+xyPoints.y);
self.emit('added', self.xyPoints);
});
};
 
//create an instance of Heatmap
//we'll use this in the requests
var MyHeatmap = new Heatmap();
 
//get datapoints from querystring
//save datapoinst to file
//and emit event
var addDataPoint = function(req, res){
var formData = [];
var urlObj = Url.parse(req.url, true);
if (urlObj.query["x"] === undefined) {
res.end('0');
return;
}
if (urlObj.query["y"] === undefined) {
res.end('0');
return;
}
formData.x = urlObj.query["x"];
formData.y = urlObj.query["y"];
MyHeatmap.add(formData);
res.end('1');
};
 
//responds to request when new click is sent
//to /addDataPoint, otherwise hangs
var displayNewDataPoints = function(req, res) {
MyHeatmap.on('added', function(dt) {
//console.log('displaying new points. x: '+dt.x + ' y:'+dt.y);
//print client side js so client heatmap
//display functions are called
//and recall this url again
var str = 'xx.addDataPoint('+dt.x+","+dt.y+');';
str += 'ajad_send(nurl);';
res.write(str,'utf8');
res.end();
});
};
 
//@todo display heatmap using last n dataPoints from file
var displayCurrentDataPoints = function(req, res) {
fs.readFile("./clickcount.txt", function(err, data){
res.write( data.toString() );
res.end();
});
 
};
 
//basic basic routing
var router = { "/" : displayCurrentDataPoints,
"/addDataPoint" : addDataPoint,
"/newDataPoints" : displayNewDataPoints
};
 
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/javascript'});
var requestPath = Url.parse(req.url).pathname;
console.log(requestPath);
try {
router[requestPath](req, res);
} catch(e) {
res.end('');
}
}).listen(8000);

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.