Marin
Marin

Reputation: 1020

NodeJS server executes two times?

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

Answers (3)

Leet Hudka
Leet Hudka

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

kimk
kimk

Reputation: 116

No, dont execute 2 times. Executes only 1 time. If you execute console.log(request.url); you know this.

Upvotes: 1

mscdex
mscdex

Reputation: 106696

Try adding console.log(request.url);. I'm betting that the browser is checking for favicon.ico also.

Upvotes: 2

Related Questions