Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adds a note about stop garbage collection #364

Merged
merged 1 commit into from Nov 26, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
12 changes: 10 additions & 2 deletions README.md
Expand Up @@ -21,12 +21,20 @@ npm install fsevents

```js
const fsevents = require('fsevents');

// To start observation
const stop = fsevents.watch(__dirname, (path, flags, id) => {
const info = fsevents.getInfo(path, flags, id);
}); // To start observation
stop(); // To end observation
});

// To end observation
stop();
```

> **Important note:** The API behaviour is slightly different from typical JS APIs. The `stop` function **must** be
> retrieved and stored somewhere, even if you don't plan to stop the watcher. If you forget it, the garbage collector
> will eventually kick in, the watcher will be unregistered, and your callbacks won't be called anymore.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm wondering, maybe this note could be reflected in the sample code?
Something like:

const watchers = {};

const logAndWatch = (path) => {
    console.log('Watching ' + path)
    const stop = fsevents.watch(__dirname, (path, flags, id) => {
        const info = fsevents.getInfo(path, flags, id);
        console.dir(info);
    });
    watchers[path] = stop;
}

// Start observation and store the watcher
let myPath = '/path/to/somefile.txt';
logAndWatch(myPath);

// End observation, and get rid of the watcher
watchers[myPath]();
watchers[myPath] = null;

It's not as sweet as the original 4-liner, but can prevent some head scratching.

It seems inevitable to have to use an array or object to store the stop reference, otherwise in a local function the ref will go out of scope.

The callback passed as the second parameter to `.watch` get's called whenever the operating system detects a
a change in the file system. It takes three arguments:

Expand Down