Skip to content

Commit 9df1e8f

Browse files
mcollinagibfahn
authored andcommitted
console: avoid adding infinite error listeners
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 <jasnell@gmail.com> Reviewed-By: Anna Henningsen <anna@addaleax.net> Reviewed-By: Colin Ihrig <cjihrig@gmail.com> Reviewed-By: Anatoli Papirovski <apapirovski@mac.com> Reviewed-By: Luigi Pinca <luigipinca@gmail.com> Reviewed-By: Sam Roberts <vieuxtech@gmail.com>
1 parent edb03cb commit 9df1e8f

File tree

2 files changed

+28
-1
lines changed

2 files changed

+28
-1
lines changed

lib/console.js

+4-1
Original file line numberDiff line numberDiff line change
@@ -82,7 +82,10 @@ function createWriteErrorHandler(stream) {
8282
// an `error` event. Adding a `once` listener will keep that error
8383
// from becoming an uncaught exception, but since the handler is
8484
// removed after the event, non-console.* writes won’t be affected.
85-
stream.once('error', noop);
85+
// we are only adding noop if there is no one else listening for 'error'
86+
if (stream.listenerCount('error') === 0) {
87+
stream.on('error', noop);
88+
}
8689
}
8790
};
8891
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
'use strict';
2+
3+
const common = require('../common');
4+
const { Writable } = require('stream');
5+
const { Console } = require('console');
6+
const { EventEmitter } = require('events');
7+
8+
const stream = new Writable({
9+
write(chunk, enc, cb) {
10+
cb();
11+
},
12+
writev(chunks, cb) {
13+
setTimeout(cb, 10, new Error('kaboom'));
14+
}
15+
});
16+
const myConsole = new Console(stream, stream);
17+
18+
process.on('warning', common.mustNotCall);
19+
20+
stream.cork();
21+
for (let i = 0; i < EventEmitter.defaultMaxListeners + 1; i++) {
22+
myConsole.log('a message');
23+
}
24+
stream.uncork();

0 commit comments

Comments
 (0)