diff --git a/lib/watch.js b/lib/watch.js index 6fe04ff..554a3b5 100644 --- a/lib/watch.js +++ b/lib/watch.js @@ -231,8 +231,11 @@ Watcher.prototype.close = function(fullPath) { // Do not close the Watcher unless all child watchers are closed. // https://github.com/yuanchuan/node-watch/issues/75 if (is.emptyObject(self.watchers)) { - this._isClosed = true; - process.nextTick(emitClose, this); + // should emit once + if (!this._isClosed) { + this._isClosed = true; + process.nextTick(emitClose, this); + } } } @@ -385,6 +388,12 @@ Watcher.prototype.watchDirectory = function(dir, options, fn, counter = nullCoun delete opts.recursive; } + // check if it's closed before calling watch. + if (self._isClosed) { + done(); + return self.close(); + } + var watcher = fs.watch(dir, opts); self.add(watcher, { diff --git a/test/test.js b/test/test.js index 20290e5..9c19965 100644 --- a/test/test.js +++ b/test/test.js @@ -696,6 +696,17 @@ describe('watcher object', function() { }); }); + it('should not watch after .close() is called', function(done) { + var dir = tree.getPath('home'); + watcher = watch(dir, { delay: 0, recursive: true }); + watcher.close(); + + watcher.getWatchedPaths(function(dirs) { + assert(dirs.length === 0); + done(); + }); + }); + it('Do not emit after close', function(done) { var dir = tree.getPath('home/a'); var file = 'home/a/file1'; @@ -720,6 +731,7 @@ describe('watcher object', function() { }, 100); }); }); + }); describe('getWatchedPaths()', function() {