Double Console Output

Node.js double console.log output

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);

my console.log() shows up twice in my chrome console

It's likely because react now wraps your application in <React.StrictMode>, strict mode combined with the browser having react dev tools will starts calling components multiple times for debugging purposes. This won't happen in a production build.

Why does my create-react-app console.log twice?

This is on purpose, it's part of React.StrictMode (specifically to detect unexpected side effects):

Strict mode can’t automatically detect side effects for you, but it
can help you spot them by making them a little more deterministic.
This is done by intentionally double-invoking the following functions:

  • Class component constructor, render, and shouldComponentUpdate methods
  • Class component static getDerivedStateFromProps method
  • Function component bodies
  • State updater functions (the first argument to setState)
  • Functions passed to useState, useMemo, or useReducer

If you remove the StrictMode element from index.js, you'll see the output only gets logged once:

ReactDOM.render(<App />, document.getElementById('root'));

Note that in strict mode this only happens in development, not in production.

Why is console.log logging twice in react js?

The render function is a lifecycle function, called during the "render phase"

Sample Image

react lifecycle methods diagram

Notice that these functions are pure functions, and can be paused, aborted, or restarted by React. This means react can call render almost any number of times to reconcile the virtualDOM with the actual DOM.

Detecting unexpected side effects

Strict mode can’t automatically detect side effects for you, but it
can help you spot them by making them a little more deterministic.
This is done by intentionally double-invoking the following functions:

  • Class component constructor, render, and shouldComponentUpdate methods
  • Class component static getDerivedStateFromProps method
  • Function component bodies
  • State updater functions (the first argument to setState)
  • Functions passed to useState, useMemo, or useReducer

Note:


This only applies to development mode. Lifecycles will not be
double-invoked in production mode.

If you truly want a one-to-one console log when the component updates use one of the other lifecycle functions, like componentDidUpdate to do the side-effect of logging details.

class Counter extends Component {
state = {
count: 0
};

componentDidUpdate() {
console.log("random-text");
}

render() {
return (
<div>
<span className={this.getBaadgeClasses()}>{this.formatCount()}</span>
<button onClick={this.handleIncrement} className="btn btn-success m-2">
Increment
</button>

{/* <ul>
{this.state.tags.map((tag) => (
<li key={tag}>{tag}</li>
))}
</ul> */}
</div>
);
}

getBaadgeClasses() {
let classes = "badge m-2 badge-";
classes += this.state.count === 0 ? "warning" : "primary";
return classes;
}

formatCount() {
const { count } = this.state;
return count === 0 ? "Zero" : count;
}

handleIncrement = () => {
this.setState({ count: this.state.count + 1 });
};
}

Edit use lifecycle function to log

How to print a double using Console.WriteLine in C#

To create a console application you need to have a Main function. You are not calling your other method from anywhere now. Main function is the starting point for your application.

namespace HelloWorld
{
class Hello
{
static void Main(string[] args)
{
System.Console.WriteLine("Hello World!");
}
}
}

See how the write line is inside the Main method? You have to write you code there and call methods or create instances there.

Why does this console log twice?

You're removing listeners from the proc instead of from stdout. The doubles are appearing because you're attaching a second copy of your listener to the 'data' events on the proc.stdout.

Adding .stdout in rmAllListeners fixes it for me:

diff --git a/why-log-twice.js b/why-log-twice.js
index 276d15c..6c15467 100644
--- a/why-log-twice.js
+++ b/why-log-twice.js
@@ -7,7 +7,7 @@ const PROC_ONE_PATH = `node child-proc "Proc 1 log # "`
const PROC_TWO_PATH = `node child-proc "Proc 2 log # "`

// rmAllListeners :: childProc -> childProc
-const rmAllListeners = proc => (proc.removeAllListeners(), proc.stdout.unref())
+const rmAllListeners = proc => (proc.stdout.removeAllListeners(), proc.stdout.unref())

// procIsReady :: string -> bool
const procIsReady = str => str.includes('5')

Why is there a double console.log?

Your browser is looking for the favicon.ico, then it sends a request for the actual content. Try to console.log both the request and response to get more information.



Related Topics



Leave a reply



Submit