Vladimir Melekh Vladimir Melekh - 1 year ago 34
Javascript Question

Use Chokidar for watching over files with specific extentions

I need to add support for this feature to my app.
My current implementation is very simple:

this.watcher.on("add", (pathName: string) => {
this.sendNotifyAction(new NotifyAction(PathEvent.Add, pathName));
}).on("change", (pathName: string) => {
this.sendNotifyAction(new NotifyAction(PathEvent.Change, pathName));
}).on("unlink", (pathName: string) => {
this.sendNotifyAction(new NotifyAction(PathEvent.Delete, pathName));
}).on("ready", () => {

Now I want to have something like:

private acceptedFileExtensions: string[] = ['.txt', '.docx', '.xlx', ...]

And use this array of extensions inside Chokidar. So if the file in watched directory has extension from the list - send notification, if no - do nothing.

I saw similar question https://stackoverflow.com/questions/40468608/use-chokidar-to-watch-for-specific-file-extension#=, but it's not what I really need.

Filtering inside callback functions doesn't look good for me, but I don't see other variants. Please advise.

Thank you.

Answer Source

Thank you @robertklep, chokidar works with arrays. So my code looks like:

private buildWildcardList(path:string): string[] {
        let result: string[] = [];
        _.each(this.acceptedFileExtensions, (extension: string) => {
           result.push(path + '/**/*' + extension);

       return result;

let wildcardList: string[] = this.buildWildcardList(path);
this.watcher = chokidar.watch(wildcardList, watchOptions);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download