1

I'm watching multiple network folders using fs.watch(), each on a different IP. The problem is that sometimes these network drives go offline, and I need to retry watching them until they go online.

The code I wrote looks like this:

watchFolder() {
    var self = this
    let path = `\\\\${this.pathIP}\\folder1`
    try {
        fs.watch(path, (eventType, filename) => {
        ...
        }
    }
    catch (err) {
        //drive is offline
        setTimeout ( () => {
            this.watchFolder()
        }, 1000);
    }
}

I tried calling the same function from the catch every second, so that if it goes online it would continue normally, but apparently this takes too much memory because of the recursion. What can be an alternative way to do what I am trying to achieve?

user2979612
  • 177
  • 11

1 Answers1

0

One solution is to refactor your code into a loop, avoiding recursion, and to use the new sleep feature in JS to implement delay.

let keep_checking = true;
while (keep_checking) { // exit condition

    let path = `\\\\${this.pathIP}\\folder1`
    try {
        fs.watch(path, (eventType, filename) => {
            // Drive is online, do stuff
            // ...
            // Remember to set the exit condition
            // eg. keep_checking = false;
        }
    }
    catch (err) {
        // Drive is offline
        await sleep(1000);
    }

}

This post gives a bit more details on the usage of sleep: What is the JavaScript version of sleep()?