Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable is incremented twice in node.js http callback function

I was playing around with node.js and something strange happens when you run this code:

var http = require("http");
var i = 0;

function onRequest(request, response) {  
  response.writeHead(200, {"Content-Type": "text/plain"});
  response.write("You're number " + i++);
  response.end();
}

http.createServer(onRequest).listen(8888);

I would expect it to behave like a page views counter, but with each refresh of the browser tab i get the result of what seems to be i=i+2 instead of a simple increment. Could someone explain this behavior to me?

like image 829
Bogdan Păun Avatar asked Apr 12 '12 20:04

Bogdan Păun


2 Answers

Your browser is hitting your server for favicon.ico as well. Each request increments i, and the request for favicon.ico counts.

Use a tool such as Fiddler or WireShark to see this behavior yourself.

like image 190
Brad Avatar answered Sep 29 '22 03:09

Brad


I bet it's the favicon request that browsers love to send over and over again.

like image 44
Corbin Avatar answered Sep 29 '22 04:09

Corbin