Reputation: 1020
I tried to develop a basic HTTP server with follow code:
var http = require("http");
http.createServer(function(request, response) {
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("Hello World");
response.end();
}).listen(8888);
And works fine and page return: Hello World
After that i tried to understand the infinite cycle in NodeJS server and discover that: when use this code:
var http = require("http");
var n = 1;
http.createServer(function(request, response) {
n++;
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("Hello World");
console.log('call: %d', n);
response.end();
}).listen(8888);
And works fine page return: Hello World
But seeing the log i found a strange result, when page refresh. call: 2 call: 3 Basically at every call (page refresh) the server executes two times, why? This is the number of threads that run at every call?
Upvotes: 1
Views: 1147
Reputation: 226
Try like this:
var http = require("http");
var n = 1;
http.createServer(function(request, response) {
if(request.url != '/favicon.ico')
{
n++;
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("Hello World");
console.log('call: %d', n);
response.end();
}
}).listen(8888);
Upvotes: 2
Reputation: 116
No, dont execute 2 times. Executes only 1 time. If you execute console.log(request.url); you know this.
Upvotes: 1
Reputation: 106696
Try adding console.log(request.url);
. I'm betting that the browser is checking for favicon.ico
also.
Upvotes: 2