Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to close fs.watch listener for a folder

I have an application that allows a user to continuously upload the contents of a local folder to a folder in the cloud. The application is built with electron and node.js

So the code that I need help with is this:

  fs.watch(getHomeDirectory(), (eventname, filename) => {
   upload(
    filename,
    `${getHomeDirectory()}/${filename}`
  );
})

This function is called as apart of a event listener on a button.

There is a getter, getHomeDirectory, function that gets the user's directory for the folder and then the upload function that uploads files that are added or changed in that folder.

I want it so that the application just keeps uploading files whenever a file is added or changed into the target directory.

Right now it works, but I want the user to be able to shut off the fs.watch so they stop listening to the folder.

I had found this stack overflow question: NodeJS: unwatching a file and specifying a listener. However this only deals with fs.watchFile and when I tried doing the same for fs.watch it did not work.

I don't know what I need to do.

like image 698
Grant Herman Avatar asked Dec 31 '18 03:12

Grant Herman


1 Answers

fs.watch(...) returns an instance of fs.FSWatcher, which has a .close() method. So, if you want to unwatch you can:

const watcher = fs.watch(getHomeDirectory(), (eventname, filename) => {
  // your code here
})

Then, when you're done with the watcher, you would call:

watcher.close()
like image 190
kevin.groat Avatar answered Sep 23 '22 17:09

kevin.groat