Skip to content

Instantly share code, notes, and snippets.

@hubgit
Created May 13, 2010 14:42
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save hubgit/399898 to your computer and use it in GitHub Desktop.
Save hubgit/399898 to your computer and use it in GitHub Desktop.
A basic visitor counter for Node.js, storing counters in Redis
// embed an img element in an HTML page, point it at this.
var sys = require("sys"), http = require("http"), crypto = require("crypto");
var db = require("redis-client").createClient();
http.createServer(function(request, response) {
var date = new Date;
var day = date.getUTCFullYear() + "-" + (date.getUTCMonth() + 1) + "-" + date.getUTCDate();
var urlhash = crypto.createHash("md5").update(request.headers.referer).digest("hex");
var keys = [
"hits-by-url:" + urlhash,
"hits-by-day:" + day,
"hits-by-url-by-day:" + urlhash + ":" + day
];
for (i in keys)
db.incr(keys[i]);
response.writeHead(200, { "Content-Type": "image/gif" });
response.write("BINARY GIF DATA HERE", "binary");
response.end();
}).listen(8181);
sys.puts("Server running at http://0.0.0.0:8181/");
@zladuric
Copy link

zladuric commented Oct 6, 2015

Missing check for actual req.headers.referer, not all user-agents set it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment