Skip to content

Commit

Permalink
events: make sure console functions exist
Browse files Browse the repository at this point in the history
If there's no global console cached, initialize it.

Fixes: #4467
PR-URL: #4479
Reviewed-By: Roman Reiss <me@silverwind.io>
Reviewed-By: James M Snell <jasnell@gmail.com>
  • Loading branch information
Dave authored and evanlucas committed Jan 18, 2016
1 parent 056b078 commit a8330f7
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 1 deletion.
15 changes: 14 additions & 1 deletion lib/events.js
Expand Up @@ -18,7 +18,20 @@ EventEmitter.prototype._maxListeners = undefined;


// By default EventEmitters will print a warning if more than 10 listeners are // By default EventEmitters will print a warning if more than 10 listeners are
// added to it. This is a useful default which helps finding memory leaks. // added to it. This is a useful default which helps finding memory leaks.
EventEmitter.defaultMaxListeners = 10; var defaultMaxListeners = 10;

Object.defineProperty(EventEmitter, 'defaultMaxListeners', {
enumerable: true,
get: function() {
return defaultMaxListeners;
},
set: function(arg) {
// force global console to be compiled.
// see https://github.com/nodejs/node/issues/4467
console;
defaultMaxListeners = arg;
}
});


EventEmitter.init = function() { EventEmitter.init = function() {
this.domain = null; this.domain = null;
Expand Down
36 changes: 36 additions & 0 deletions test/parallel/test-global-console-exists.js
@@ -0,0 +1,36 @@
/* eslint-disable required-modules */
// ordinarily test files must require('common') but that action causes
// the global console to be compiled, defeating the purpose of this test

'use strict';

const assert = require('assert');
const EventEmitter = require('events');
const leak_warning = /EventEmitter memory leak detected\. 2 hello listeners/;

var write_calls = 0;
process.stderr.write = function(data) {
if (write_calls === 0)
assert.ok(data.match(leak_warning));
else if (write_calls === 1)
assert.ok(data.match(/Trace/));
else
assert.ok(false, 'stderr.write should be called only twice');

write_calls++;
};

const old_default = EventEmitter.defaultMaxListeners;
EventEmitter.defaultMaxListeners = 1;

const e = new EventEmitter();
e.on('hello', function() {});
e.on('hello', function() {});

// TODO: figure out how to validate console. Currently,
// there is no obvious way of validating that console
// exists here exactly when it should.

assert.equal(write_calls, 2);

EventEmitter.defaultMaxListeners = old_default;

0 comments on commit a8330f7

Please sign in to comment.