Watching directory with fs.watch not closing prev. watchers

#1

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);
                }
            });
        }
    });
0 Likes

#2

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.

0 Likes

#3

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:

0 Likes

#4

In the close event handler on the node: https://nodered.org/docs/creating-nodes/node-js#closing-the-node

1 Like

#5

aaah, genius. Thanks!

0 Likes

#6

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

0 Likes

#7

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

I got it working now :slight_smile:

0 Likes

#8

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

0 Likes