yuanchuan / node-watch

A wrapper and enhancements for fs.watch
https://npm.im/node-watch
MIT License
340 stars 44 forks source link

Add an extra flag for skipping sub-directories inside filter function. #101

Closed yuanchuan closed 4 years ago

yuanchuan commented 4 years ago

This is an attempt to fix #93 by introducing a third return value. For example:

let options = {
  recursive: true,
  // watch all js files and skip node_modules
  filter(name) {
    if (/node_modules/.test(name)) {
      // skip to watch all the the sub-directories if it's on Linux
      return 'skip';
    }
    if (/\.js$/.test(name)) {
      // as before
      return true;
    }
  }
}

watch('./', options, console.log);

I couldn't find a way to write a test at this moment


update

Now this is how to ignore and skip to watch the node_modules directory.

let options = {
  recursive: true,
  filter(name, skip) {
    if (/\/node_modules/.test(name)) return skip;
    return true;
  }
}

watch('./', options, console.log)

In order to test it I've also added a new method to get all the watched paths.

let watcher = watch('./', options, console.log);

watcher.getWatchedPaths(function(paths) {

});
yuanchuan commented 4 years ago

The format of the flag might be something else. We need to find the most proper one.

if (condition) {
  return { skip: true };
}

or

if (condition) {
  return -1;
}

or pass the variable to use

filter(name, skip) {
  if (condition) {
    return skip;
  }
}

or

filter(name, flag) {
  if (condition) {
    return flag.skip;
  }
}

etc.

wmertens commented 4 years ago

I like passing the skip parameter - it's impossible to return the skip value by accident for existing users, you don't have to remember special values, and it's easy to read.

So if you only want to see changes to .js files that are not in node_modules, you'd have

filter: (name, skip) => {
  if (name==='node_modules') return skip
  return /\.js$/i.test(name)
}

I think this reads nicely, even though the skip value is truthy and would normally mean it passes

wmertens commented 4 years ago

This is great :) now how to test it...

yuanchuan commented 4 years ago

Would love to see your review @Krinkle :)

yuanchuan commented 4 years ago

It took too long! I'm about to merge this PR. Hope there will be a better solution in the future. Thank you so much!