fswatcher
Cross-platform file system notifications for Go.
Previously published asgithub.com/gofsnotify/fsnotify(packagefsnotify). The old path is deprecated and redirects here; update imports and renamefsnotify.Xtofswatcher.X. See #27.
Install
go get github.com/fswatcher/fswatcher
Usage
package main
import (
"log"
"github.com/fswatcher/fswatcher"
)
func main() {
w, err := fswatcher.NewWatcher()
if err != nil {
log.Fatal(err)
}
defer w.Close()
if err := w.Add("/path/to/dir", fswatcher.Create|fswatcher.Write|fswatcher.Remove); err != nil {
log.Fatal(err)
}
for {
select {
case ev := <-w.Events:
log.Println(ev)
case err := <-w.Errors:
log.Println("error:", err)
}
}
}
API
NewWatcher() (*Watcher, error)— creates a watcher.(*Watcher).Add(path string, op Op) error— registerspathwith the given event mask. ReturnsErrAlreadyAddedifpathis already registered.(*Watcher).AddRecursive(path string, op Op) error— registerspathand every directory under it. New subdirectories created inside are watched automatically; removed subdirectories are dropped.Removemay only be called on the original recursive root.(*Watcher).Remove(path string) error— unregisterspath. For anAddRecursiveregistration this drops the entire subtree.(*Watcher).Close() error— stops the watcher and closes the channels.(*Watcher).Events <-chan Event— receives change notifications.(*Watcher).Errors <-chan error— receives non-fatal errors.Canonicalize(path string) (string, error)— returns the form fswatcher uses internally forAdd,Remove, andEvent.Name. Use it to align a watched root with the paths in event names, for example when computing relative paths or applying an ignore list.
Event.Name is always returned in canonical form.
Events
| Op | Description | |--------|---------------------------------------------| | Create | A file or directory was created. | | Write | A file's contents were modified. | | Remove | A file or directory was removed. | | Rename | A file or directory was renamed or moved. | | Chmod | Permissions or attributes changed. |
Op is a bitmask; combine values with | when calling Add. The All constant is shorthand for the union of every Op bit.
Guarantees
- Thread-safe: methods may be called from multiple goroutines.
- Event ordering is preserved as far as the underlying OS allows.
- Behavior is normalized across supported platforms.
Platform Support
| OS | Backend | Status | |---------|-------------------------|-----------| | Linux | inotify | Supported | | Windows | ReadDirectoryChangesW | Supported | | macOS | FSEvents (purego) | Supported | | FreeBSD | kqueue | Supported |
License
MIT