yuanchuan / node-watch

A wrapper and enhancements for fs.watch

Home Page:https://npm.im/node-watch

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Double change event with multiple file patterns

stil4m opened this issue · comments

The following snippet will give me double change events if I change a file in the files directory:

const watcher = watch([".", "files/"], { recursive: true });

Is this by design or a bug? Both the patterns will match on a file in the files directory, but I would expect that duplicate events are removed.

Since you are recursively watch ./ directory, the files/ folder inside it will also be watched.

You should just watch ./:

const watcher = watch('./', { recursive: true });

or remove the recursive option

const watcher = watch([".", "files/"])

I understand the recursiveness. My problem is however that the patterns I have to watch are not in my code base, but are user input. It is hard to filter out overlapping file patterns. But as I thus understand it is by design? E.g. the following snippets are semantically equivalent:

const x = function(event, name) {
 ...
}
const watcher = watch([".", "files/"], { recursive: true });

watcher.onChange(x);
const x = function(event, name) {
 ...
}
const watcherA = watch(".", { recursive: true });
const watcherB = watch("files/", { recursive: true });

watcherA.onChange(x);
watcherB.onChange(x);

This is no problem (and I understand this decision), but in that case I may have to change library or implement some 'overlapping pattern' algorithm myself.

Yes it is by design, they are two separate watchers combined into one.

Does debounce help?

Debounce will stall emitting the event until for a X amount of time no changes for a file are detected?

If that is the case, it will help depending on the time of delay.

My use case is that I have to watch some patterns, and on these changes analyse the files and send these results to a UI or an editor. Every bit of delay is a bit too much. Do you know what a reasonable delay is to use to dedup the event?

Using a higher-order function to filter duplicate events:

function filterDups(fn) {
  let names = {};
  return (...args) => {
    names[args.join('')] = args;
    setTimeout(() => {
      Object.keys(names).forEach(n => fn.apply(null, names[n]));
      names = {};
    }, 50);
  }
}

const watcher = watch(['.', 'files/'], { recursive: true });

watcher.on('change', filterDups(function(evt, name) {
  console.log(evt, name);
}));

Ok thanks. I will try that.

Sorry @stil4m. After carefully thought I think it's quite reasonable to remove duplicate events inside node-watch.

I'll try to fix it and publish a new version.

You dont have to say sorry :). It is a hard problem to fix.

Please try v0.5.5

@stil4m Did it work?

Received a comment last night: stil4m/elm-analyse#88 (comment). Seems to work. Thanks!