diff --git a/lib/internal/console/constructor.js b/lib/internal/console/constructor.js index 04b6087b77f780..9c262aef62be25 100644 --- a/lib/internal/console/constructor.js +++ b/lib/internal/console/constructor.js @@ -231,7 +231,8 @@ Console.prototype[kWriteToConsole] = function(streamSymbol, string) { // handle both situations. try { // Add and later remove a noop error handler to catch synchronous errors. - stream.once('error', noop); + if (stream.listenerCount('error') === 0) + stream.once('error', noop); stream.write(string, errorHandler); } catch (e) { diff --git a/test/parallel/test-worker-console-listeners.js b/test/parallel/test-worker-console-listeners.js new file mode 100644 index 00000000000000..9f0d6e4824ed7e --- /dev/null +++ b/test/parallel/test-worker-console-listeners.js @@ -0,0 +1,16 @@ +'use strict'; +const common = require('../common'); +const { Worker, isMainThread } = require('worker_threads'); +const EventEmitter = require('events'); + +if (isMainThread) { + process.on('warning', common.mustNotCall('unexpected warning')); + + for (let i = 0; i < EventEmitter.defaultMaxListeners; ++i) { + const worker = new Worker(__filename); + + worker.on('exit', common.mustCall(() => { + console.log('a'); // This console.log() is part of the test. + })); + } +}