diff --git a/lib/fs.js b/lib/fs.js index a965c84afc..a9e96bd736 100644 --- a/lib/fs.js +++ b/lib/fs.js @@ -1393,6 +1393,10 @@ fs.watch = function(filename, options, listener) { // Stat Change Watchers +function emitStop(self) { + self.emit('stop'); +} + function StatWatcher() { EventEmitter.call(this); @@ -1413,7 +1417,7 @@ function StatWatcher() { }; this._handle.onstop = function() { - self.emit('stop'); + process.nextTick(emitStop, self); }; } util.inherits(StatWatcher, EventEmitter); diff --git a/test/parallel/test-fs-watch-stop-async.js b/test/parallel/test-fs-watch-stop-async.js new file mode 100644 index 0000000000..5cbfd58418 --- /dev/null +++ b/test/parallel/test-fs-watch-stop-async.js @@ -0,0 +1,19 @@ +'use strict'; +const common = require('../common'); +const assert = require('assert'); +const fs = require('fs'); + +const watch = fs.watchFile(__filename, () => {}); +let triggered; +const listener = common.mustCall(() => { + triggered = true; +}); + +triggered = false; +watch.once('stop', listener); // Should trigger. +watch.stop(); +assert.equal(triggered, false); +setImmediate(() => { + assert.equal(triggered, true); + watch.removeListener('stop', listener); +}); diff --git a/test/parallel/test-fs-watch-stop-sync.js b/test/parallel/test-fs-watch-stop-sync.js new file mode 100644 index 0000000000..1444ff6bfd --- /dev/null +++ b/test/parallel/test-fs-watch-stop-sync.js @@ -0,0 +1,9 @@ +'use strict'; +require('../common'); +const assert = require('assert'); +const fs = require('fs'); + +const watch = fs.watchFile(__filename, () => {}); +watch.once('stop', assert.fail); // Should not trigger. +watch.stop(); +watch.removeListener('stop', assert.fail);