Skip to content

Commit

Permalink
console: avoid adding infinite error listeners
Browse files Browse the repository at this point in the history
If the console destination is a unix pipe (net.Socket), write() is
async. If the destination is broken, we are adding an 'error' event
listener to avoid a process crash. This PR makes sure that we are adding
that listener only once.

Fixes: #16767

PR-URL: #16770
Fixes: #16767
Reviewed-By: James M Snell <[email protected]>
Reviewed-By: Anna Henningsen <[email protected]>
Reviewed-By: Colin Ihrig <[email protected]>
Reviewed-By: Anatoli Papirovski <[email protected]>
Reviewed-By: Luigi Pinca <[email protected]>
Reviewed-By: Sam Roberts <[email protected]>
  • Loading branch information
mcollina authored and gibfahn committed Nov 8, 2017
1 parent edb03cb commit 9df1e8f
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 1 deletion.
5 changes: 4 additions & 1 deletion lib/console.js
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,10 @@ function createWriteErrorHandler(stream) {
// an `error` event. Adding a `once` listener will keep that error
// from becoming an uncaught exception, but since the handler is
// removed after the event, non-console.* writes won’t be affected.
stream.once('error', noop);
// we are only adding noop if there is no one else listening for 'error'
if (stream.listenerCount('error') === 0) {
stream.on('error', noop);
}
}
};
}
Expand Down
24 changes: 24 additions & 0 deletions test/parallel/test-console-log-stdio-broken-dest.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
'use strict';

const common = require('../common');
const { Writable } = require('stream');
const { Console } = require('console');
const { EventEmitter } = require('events');

const stream = new Writable({
write(chunk, enc, cb) {
cb();
},
writev(chunks, cb) {
setTimeout(cb, 10, new Error('kaboom'));
}
});
const myConsole = new Console(stream, stream);

process.on('warning', common.mustNotCall);

stream.cork();
for (let i = 0; i < EventEmitter.defaultMaxListeners + 1; i++) {
myConsole.log('a message');
}
stream.uncork();

0 comments on commit 9df1e8f

Please sign in to comment.