3

I did some experiment with node earlier

The following code outputs "aaa" to console, and the browser keeps waiting for response, as expected.

var http = require("http");

http.createServer(function (req, res) {
  //res.writeHead(200);
  console.log("aaa");
  //res.end("hello");
  //console.log("test111");
  //res.end("bye");
}).listen(5555);

Output:

aaa

But, as soon as I un-comment the first res.end, node writes "aaa" to the console twice on one request!

var http = require("http");

http.createServer(function (req, res) {
  res.writeHead(200);
  console.log("aaa");
  res.end("hello");
  //console.log("test111");
  //res.end("bye");
}).listen(5555);

Output:

aaa
aaa

Finally, when I un-comment everything,

var http = require("http");

http.createServer(function (req, res) {
  res.writeHead(200);
  console.log("aaa");
  res.end("hello");
  console.log("test111");
  res.end("bye");
}).listen(5555);

Output:

aaa
test111
aaa
test111

Any idea why the console.log statements are executed twice per single request?

Max
  • 1,399
  • 13
  • 28

2 Answers2

8

In the first example, the browser doesn't get a reply and stops there.

In the second example, the browser does get a reply, and then goes on to request the favicon which is a second request.

Try to also log the request url:

var http = require("http");
http.createServer(function (req, res) {
  console.log("aaa", req.url);
  res.end("bye");
}).listen(5555);

and you'll see the server going:

aaa /
aaa /favicon.ico
Deestan
  • 16,738
  • 4
  • 32
  • 48
5

This has the answer you're looking for:

NodeJS server incrementing variable by two for every request

It is hitting / and /favicon.ico.

Community
  • 1
  • 1
Steve McGuire
  • 1,467
  • 12
  • 8