14

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.

Grant Herman
  • 923
  • 2
  • 13
  • 29
  • Have you looked at [**https://nodejs.org/docs/latest/api/fs.html#fs_event_close**](https://nodejs.org/docs/latest/api/fs.html#fs_event_close) – NewToJS Dec 31 '18 at 03:35

1 Answers1

24

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()
kevin.groat
  • 1,274
  • 12
  • 21
  • I am not sure if it is the correct answer because `watcher=...` is asynchronous and `watcher.close()` will close immediately – Chau Giang Oct 12 '21 at 21:39
  • I've updated the answer to be more clear on the fact that `watcher.close()` shouldn't be called immediately afterward. – kevin.groat Oct 13 '21 at 19:13