Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 304
JDillon522 Avatar asked Jul 30 '13 16:07

JDillon522


2 Answers

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);
like image 106
c.P.u1 Avatar answered Sep 17 '22 17:09

c.P.u1


I've had the same problem myself, and I found out that using something like

var http = require('http');
http.createServer(function(req,res) {
    if(req.url === '/favicon.ico')
    {
        //everything here is ignored
    }
    res.writeHead(200,{"Content-Type": "text/plain"});
res.write("Hello World\n");
res.end();
console.log("Connection made");
}).listen(1337, "127.0.0.1");
console.log("Server running at http://127.0.0.1:1337/");

is enough to avoid that behaviour. For some reason, when I check req.url and compare it to '/favicon.ico' nothing is sent to console, in fact, everything in that block is ignored. I don't know if this behaviour is expected, but you sure could try it.

like image 31
Budgerous Avatar answered Sep 20 '22 17:09

Budgerous