Search code examples
javascriptnode.jshttpnodesnode-modules

Nodejs Http Server api Execution flow please Explain?


I am having the following Nodejs Program

var http = require('http');
var url = require('url');
var server = http.createServer((req,res)=>{
  console.log("Enter into the 3000 port");
  res.end("hello world")
  console.log("Enter into the 3000 port");
}).listen(3000,()=>{console.log("the server is listen to the port 3000");});

I am running these code while loading the localhost:3000 in browser and when i written the console.log("Enter into the 3000 port"); to check how the execution works internally i got the following output. OUTPUT:

the server is listen to the port 3000
Enter into the 3000 port
Enter into the 3000 port
Enter into the 3000 port
Enter into the 3000 port

But i have written the code console.log("Enter into the 3000 port"); two times in code but i don't understand why it called two times on single request and when i again send the request it again showed me the some output can any one explain.


Solution

  • var http = require('http');
    var url = require('url');
    var server = http.createServer((req,res)=>{
      if (req.url === '/favicon.ico') { return } // if you don't serve this hit 
      console.log(req.url);
      console.log("Enter into the 3000 port");
      res.end("hello world")
      console.log("Enter into the 3000 port");
    }).listen(3000,()=>{console.log("the server is listen to the port 3000");})
    

    enter image description here

    most of the browsers look for *favicon.ico* automatically you can avoid if you want

    code