Skip to content

Commit ad96e3f

Browse files
authored
Fix: Only emit error events when there is a listener (fixes #35) (#36)
1 parent 783e42f commit ad96e3f

File tree

2 files changed

+26
-2
lines changed

2 files changed

+26
-2
lines changed

index.js

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,18 @@ var defaultOpts = {
1212
queue: true,
1313
};
1414

15+
function listenerCount(ee, evtName) {
16+
if (typeof ee.listenerCount === 'function') {
17+
return ee.listenerCount(evtName);
18+
}
19+
20+
return ee.listeners(evtName).length;
21+
}
22+
23+
function hasErrorListener(ee) {
24+
return listenerCount(ee, 'error') !== 0;
25+
}
26+
1527
function watch(glob, options, cb) {
1628
if (typeof options === 'function') {
1729
cb = options;
@@ -32,7 +44,7 @@ function watch(glob, options, cb) {
3244
function runComplete(err) {
3345
running = false;
3446

35-
if (err) {
47+
if (err && hasErrorListener(watcher)) {
3648
watcher.emit('error', err);
3749
}
3850

test/index.js

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -159,7 +159,7 @@ describe('glob-watcher', function() {
159159
});
160160
});
161161

162-
it('emits an error if one occurs in the callback', function(done) {
162+
it('emits an error if one occurs in the callback and handler attached', function(done) {
163163
var expectedError = new Error('boom');
164164

165165
watcher = watch(outGlob, function(cb) {
@@ -175,6 +175,18 @@ describe('glob-watcher', function() {
175175
watcher.on('ready', changeFile);
176176
});
177177

178+
it('does not emit an error (and crash) when no handlers attached', function(done) {
179+
var expectedError = new Error('boom');
180+
181+
watcher = watch(outGlob, function(cb) {
182+
cb(expectedError);
183+
setTimeout(done, timeout * 3);
184+
});
185+
186+
// We default `ignoreInitial` to true, so always wait for `on('ready')`
187+
watcher.on('ready', changeFile);
188+
});
189+
178190
it('allows the user to disable queueing', function(done) {
179191
var runs = 0;
180192

0 commit comments

Comments
 (0)