Console.log give two different output for same variable ?. How is this possible

I have a code here.

const http = require("http");

const fs = require("fs");

const json = fs.readFileSync(`${__dirname}/data/data.json`, "utf-8");

const server = http.createServer((req, res) => {
  
console.log(req);  
/*
Very big output
  maxHeadersCount: null,
      headersTimeout: 40000,
      _connectionKey: '4:127.0.0.1:1337',
      [Symbol(IncomingMessage)]: [Function: IncomingMessage],
      [Symbol(ServerResponse)]: [Function: ServerResponse],
      [Symbol(asyncId)]: 5
    }, .................................................
*/



console.log(`${req}`) // output: [object Object]



res.writeHead(200, { "Content-type": "text/html" });

  res.end("This is the response");

});

server.listen("1337", "127.0.0.1", () => {

  console.log(`Listening Request`);

});

as you can see req variable behave differently why ???

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.

Note: Backticks are not single quotes.

markdown_Forums

They aren’t the same, you’ve done clearly different things. The first one you log the object, the second one is what you get when you convert it to a string (it’s telling you it’s an object)

I will keep in mind. Thanks

Thanks for responding. So passing an object in template literals converts it into string ???

That’s what template literals are for, they build strings. And an object is just a reference, the values in the object aren’t in the same place, so it can’t give you anything else except what it is (an object) and what type of object it is (just a plain object)

Thanks so much. Muahhhhhhhhhhhhhh

Note than you can use JSON.stringify(obj) to get a string conversion that is probably closer to what you expected.

1 Like