Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Catch fs.watch exceptions #125

Merged
merged 1 commit into from
Jul 14, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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