Skip to content

Commit

Permalink
Catch fs.watch exceptions (#125)
Browse files Browse the repository at this point in the history
  • Loading branch information
campersau authored Jul 14, 2022
1 parent e226156 commit 5743e51
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 2 deletions.
22 changes: 20 additions & 2 deletions lib/watch.js
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,16 @@ function createDupsFilter() {
}
}

function tryWatch(watcher, dir, opts) {
try {
return fs.watch(dir, opts);
} catch (e) {
process.nextTick(function() {
watcher.emit('error', e);
});
}
}

function getSubDirectories(dir, fn, done = function() {}) {
if (is.directory(dir)) {
fs.readdir(dir, function(err, all) {
Expand Down Expand Up @@ -357,7 +367,11 @@ Watcher.prototype.watchFile = function(file, options, fn) {
// no need to watch recursively
delete opts.recursive;

var watcher = fs.watch(parent, opts);
var watcher = tryWatch(this, parent, opts);
if (!watcher) {
return;
}

this.add(watcher, {
type: 'file',
fpath: parent,
Expand Down Expand Up @@ -395,7 +409,11 @@ Watcher.prototype.watchDirectory = function(dir, options, fn, counter = nullCoun
return self.close();
}

var watcher = fs.watch(dir, opts);
var watcher = tryWatch(self, dir, opts);
if (!watcher) {
done();
return;
}

self.add(watcher, {
type: 'dir',
Expand Down
29 changes: 29 additions & 0 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,20 @@ describe('watch for files', function() {
}, 100);
});
});

it('should error when parent gets deleted before calling fs.watch', function(done) {
var fpath = tree.getPath('home/a/file1');
watcher = watch(fpath, Object.defineProperty({}, 'test', {
enumerable: true,
get: function() {
tree.remove('home/a');
return 'test';
}
}));
watcher.on('error', function() {
done();
});
});
});

describe('watch for directories', function() {
Expand Down Expand Up @@ -282,6 +296,21 @@ describe('watch for directories', function() {
}, 350);
});
});

it('should error when directory gets deleted before calling fs.watch', function(done) {
var dir = 'home/c';
var fpath = tree.getPath(dir);
watcher = watch(fpath, Object.defineProperty({}, 'test', {
enumerable: true,
get: function() {
tree.remove(dir);
return 'test';
}
}));
watcher.on('error', function() {
done();
});
});
});

describe('file events', function() {
Expand Down

0 comments on commit 5743e51

Please sign in to comment.