Skip to content

Commit f9a59c1

Browse files
Davejasnell
Dave
authored andcommitted
events: make sure console functions exist
If there's no global console cached, initialize it. Fixes: #4467 PR-URL: #4479 Reviewed-By: Roman Reiss <[email protected]> Reviewed-By: James M Snell <[email protected]>
1 parent 4bc1a47 commit f9a59c1

File tree

2 files changed

+50
-1
lines changed

2 files changed

+50
-1
lines changed

lib/events.js

+14-1
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,20 @@ EventEmitter.prototype._maxListeners = undefined;
1919

2020
// By default EventEmitters will print a warning if more than 10 listeners are
2121
// added to it. This is a useful default which helps finding memory leaks.
22-
EventEmitter.defaultMaxListeners = 10;
22+
var defaultMaxListeners = 10;
23+
24+
Object.defineProperty(EventEmitter, 'defaultMaxListeners', {
25+
enumerable: true,
26+
get: function() {
27+
return defaultMaxListeners;
28+
},
29+
set: function(arg) {
30+
// force global console to be compiled.
31+
// see https://github.com/nodejs/node/issues/4467
32+
console;
33+
defaultMaxListeners = arg;
34+
}
35+
});
2336

2437
EventEmitter.init = function() {
2538
this.domain = null;
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
/* eslint-disable required-modules */
2+
// ordinarily test files must require('common') but that action causes
3+
// the global console to be compiled, defeating the purpose of this test
4+
5+
'use strict';
6+
7+
const assert = require('assert');
8+
const EventEmitter = require('events');
9+
const leak_warning = /EventEmitter memory leak detected\. 2 hello listeners/;
10+
11+
var write_calls = 0;
12+
process.stderr.write = function(data) {
13+
if (write_calls === 0)
14+
assert.ok(data.match(leak_warning));
15+
else if (write_calls === 1)
16+
assert.ok(data.match(/Trace/));
17+
else
18+
assert.ok(false, 'stderr.write should be called only twice');
19+
20+
write_calls++;
21+
};
22+
23+
const old_default = EventEmitter.defaultMaxListeners;
24+
EventEmitter.defaultMaxListeners = 1;
25+
26+
const e = new EventEmitter();
27+
e.on('hello', function() {});
28+
e.on('hello', function() {});
29+
30+
// TODO: figure out how to validate console. Currently,
31+
// there is no obvious way of validating that console
32+
// exists here exactly when it should.
33+
34+
assert.equal(write_calls, 2);
35+
36+
EventEmitter.defaultMaxListeners = old_default;

0 commit comments

Comments
 (0)