JDillon522 JDillon522 - 2 months ago 21
Node.js Question

Node.js double console.log output

I'm learning Node.js and I'd like to understand the "why" when code spits out duplicated console.log outputs but only a single response.write outputs.

Heres my simple code example:

var http = require('http');

http.createServer(function(request, response){
response.writeHead(200, {'Content-type': 'text/plain'});
console.log('hello 1');
response.write('Hello world');
console.log('hello 2');
response.end();
}).listen(8000);


And on my console/terminal I get:


hello 1

hello 2

hello 1

hello 2


Thanks.

Answer

Some browsers also send a request to locate the favicon.ico file. Since the file isn't present by default, a browser(Chrome in particular) will always send two requests: one for the originally requested file and another for favicon.ico. This is a known bug in Chrome and has been fixed in version 29. Firefox, however, requests for favicon.ico only for the first request. If you console.log the request URI path, you must see a request to localhost:8000/favicon.ico.

var http = require('http');

http.createServer(function(request, response){
    response.writeHead(200, {'Content-type': 'text/plain'});
    if(request.url === '/favicon.ico') {
        console.log('Favicon was requested');
    }
    console.log('hello 1');
    response.write('Hello world');
    console.log('hello 2');
    response.end();
}).listen(8000);