Title: How to close fs.watch listener for a folder
Tags: javascript;node.js;electron;fs
Question: 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) =&gt; {
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.
Comment: 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)

Here is the accepted answer: 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) =&gt; {
// your code here
Then, when you're done with the watcher, you would call:
watcher.close()
Comment for this answer: I've updated the answer to be more clear on the fact that `watcher.close()` shouldn't be called immediately afterward.
Comment for this answer: I am not sure if it is the correct answer because `watcher=...` is asynchronous and  `watcher.close()` will close immediately


{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 1, 'CommentCount': 1, 'ContentLicense': 'CC BY-SA 4.0', 'CreationDate': '2018:00:12/31/18', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<javascript><node.js><electron><fs>', 'Title': 'How to close fs.watch listener for a folder', 'ViewCount': 6089, 'id': 53983342, 'user_AboutMe': '', 'user_AccountId': 6026818.0, 'user_DisplayName': 'Grant Herman', 'user_Reputation': 903.0, 'user_Views': 121.0, 'user_id': 4732217.0}}