Watching directory with fs.watch not closing prev. watchers

Hi,

I am struggling with a file that I am trying to watch for changes. I use the fs.watch, and listening on the 'change' event. It works fine, but when I hit the "Deploy" button in node-red, it opens another watcher, if I hit "Deploy" again, a third watcher appear. (Bonus info - i am running Linux). It seems it doesnt close the previously watchers. Do you have any suggestions?

Here is my .js code:

fs.watch(doPath, (eventType, filename) => {
        var msg = {payload: ""};
        if(eventType === 'change') {
            fs.readFile(doPath, 'utf8', (err, data) => {
                if (err) throw err;
                if(data[0] == 1) {
                    msg.payload = true;
                    node.send(msg);                              
                    node.status({fill:"green",shape:"dot",text:"digital-outputs.status.on"});       
                }
                else if (data[0] == 0) {                       
                    node.status({fill:"red",shape:"dot",text:"digital-outputs.status.off"});
                    msg.payload = false;
                    node.send(msg);
                }
            });
        }
    });

Have you added code to handle the close event on the node in order to remove the watcher? That won't happen automatically - you have to tidy up resources you create.

No, I have not. But I only want to close the watcher when I hit "deploy". Where will the correct place be, to implement that? :slight_smile:

In the close event handler on the node: JavaScript file : Node-RED

1 Like

aaah, genius. Thanks!

Though we do have watch node that does this already... does it not work for you use case ?

Maybe, but I want to make a custom node :wink:

I got it working now :slight_smile:

No problem - all good learning experience.
(but if there is problem with the existing node please let us know)

Hi,
Is it possible to use the watch node on network shares?

Thanks

Please do not post multiple times about the same issue in different places. You get better help if you keep it at one place, and won’t get several people researching/suggesting the same thing attempting to help.

1 Like