Fswatcher
Cross-platform file watcher written in Go for native concurrent monitoring
Install / Use
/learn @sgtdi/FswatcherREADME
FSWatcher
A production-ready file watcher for Go with built-in debouncing and filtering.
FSWatcher is a robust, concurrent, and cross-platform file system watcher for Go. It provides a simple and powerful API to monitor directories for file system changes, designed for high-performance applications and development tools. The goal is to abstract away the complexities of platform-specific APIs, offering a unified, easy-to-use, and dependency-free interface.
Table of contents
- Supported platforms
- Why FSWatcher
- Quick start
- What makes it different
- Options
- Methods
- Logging
- Workflow diagram
- Project structure
- Advanced usage
- FAQ
Platforms
FSWatcher uses native OS APIs for efficient, low-overhead monitoring with near-zero CPU usage when idle.
| Platform | Native System API Used | Status |
| :--- | :--- | :--- |
| ✅ macOS | FSEvents framework | Default (requires CGO) |
| | kqueue | Supported (Pure Go, no CGO) |
| ✅ BSD (FreeBSD, OpenBSD, NetBSD, DragonFly) | kqueue | Fully supported (Pure Go) |
| ✅ Linux | inotify | Fully supported |
| | fanotify | Partial support (planned for future enhancements) |
| ✅ Windows | ReadDirectoryChangesW | Fully supported |
macOS and BSD Support
On macOS, FSWatcher supports two backends:
- FSEvents (Default): Uses the native macOS FSEvents framework. Recommended for macOS — provides the most efficient and comprehensive monitoring. Requires CGO (
CGO_ENABLED=1) - kqueue (Pure Go): Uses the BSD
kernel queuenotification interface. Allows building a static binary without CGO (CGO_ENABLED=0), with a shared backend usable on FreeBSD, OpenBSD, NetBSD, and DragonFly
Why use FSEvents (CGO)?
The FSEvents API is designed specifically for file system monitoring and includes OS-level coalescing. This makes it significantly more accurate and CPU-efficient than kqueue for high-volume operations. Benchmarks show FSEvents achieves 100% path detection accuracy where kqueue may miss up to 30% of events for short-lived files under heavy load.
To use the kqueue backend on macOS, disable CGO when building:
CGO_ENABLED=0 go build
The library automatically selects the correct implementation based on the build tags. For BSD systems, kqueue is the default and only backend.
Why FSWatcher
Most Go file watchers give you raw OS events—which means duplicate events and noise from system files. FSWatcher solves this:
- Built-in debouncing - Merge rapid-fire events automatically
- Smart filtering - Regex patterns + automatic system file exclusion (
.git,.DS_Store, etc.) - Zero dependencies - Just standard library + native OS APIs
- Context-based - Modern Go patterns with graceful shutdown
Quick Start
To add FSWatcher to your project, use go get:
go get github.com/sgtdi/fswatcher
package main
import (
"context"
"fmt"
"time"
"github.com/sgtdi/fswatcher"
)
func main() {
// Create watcher with debouncing that watches the current working directory
w, _ := fswatcher.New(
fswatcher.WithCooldown(200*time.Millisecond),
)
ctx := context.Background()
go w.Watch(ctx)
fmt.Println("fswatcher started, change a file in watcher dir")
// Process clean, debounced events
for event := range w.Events() {
var types, flags []string
// Loop through types and flags
for _, t := range event.Types {
types = append(types, t.String())
}
for _, f := range event.Flags {
flags = append(flags, f)
}
fmt.Printf("File changed: %s %v %v\n", event.Path, types, flags)
}
}
What makes it different
| Feature | FSWatcher | fsnotify / notify | |---------|-----------|-------------------| | Debouncing | Built-in, configurable | Manual implementation | | Path filtering | Regex include/exclude | Manual implementation | | System files | Auto-ignored | Manual filtering | | API style | Functional options | Imperative | | Duplicate events | Handled automatically | Manual deduplication |
Options
Customize the watcher's behavior using functional options passed to fswatcher.New().
| Option | Description | Default |
|:----------------------------| :--- | :--- |
| WithPath(path, ...) | Adds an initial directory to watch. Can be called multiple times. Accepts optional PathOption values like WithDepth, WithEventMask, WithPathIncRegex, etc | Current directory |
| WithCooldown(d) | Sets the debouncing cooldown period. Events for the same path arriving within this duration will be merged | 100ms |
| WithBufferSize(size) | Sets the size of the main event channel | 4096 |
| WithIncRegex(patterns...) | Global include regex patterns — only matching paths are processed. If not set, all non-excluded paths are processed | (none) |
| WithExcRegex(patterns...) | Global exclude regex patterns — matching paths are ignored. Exclusions take precedence over inclusions | (none) |
| WithSeverity(level) | Sets the logging verbosity (SeverityDebug, SeverityInfo, SeverityWarn, SeverityError) | SeverityWarn |
| WithLogFile(path) | Sets a file for logging. Use "stdout" to log to the console or "" to disable | (disabled) |
| WithLinuxPlatform(p) | Sets a specific backend (PlatformInotify or PlatformFanotify) on Linux | PlatformInotify |
| WithDepth(depth) | Sets the watch depth for a path (WatchNested or WatchTopLevel). Passed to WithPath | WatchNested |
| WithEventMask(types...) | Filters event types for a specific path. Only the listed types are forwarded to Events(), everything else is dropped. Passed to WithPath | (all types) |
| WithPathIncRegex(patterns...) | Include regex patterns scoped to a specific path, independent of the global WithIncRegex. Passed to WithPath | (none) |
| WithPathExcRegex(patterns...) | Exclude regex patterns scoped to a specific path, independent of the global WithExcRegex. Passed to WithPath | (none) |
| WithPathFilter(filter) | Custom PathFilter implementation for a specific path. Passed to WithPath | (none) |
Methods
Once you have a Watcher instance from New(), you can use the following methods to control it:
| Method | Description |
| :--- | :--- |
| Watch(ctx) | Starts the watcher. Blocking — runs until the context is canceled. Run in a goroutine. A watcher instance is single-use: after Watch() returns, create a new watcher with New() |
| Events() | Returns a read-only channel (<-chan WatchEvent) for receiving file system events |
| AddPath(path) | Adds a new directory to monitor at runtime. Safe to call concurrently with DropPath() |
| DropPath(path) | Stops monitoring a directory at runtime. Safe to call concurrently with AddPath() |
| Close() | Initiates a graceful shutdown — alternative to canceling the context |
| IsRunning() | Returns true if Watch() is currently running |
| Stats() | Returns a WatcherStats struct with runtime statistics (uptime, events processed, etc.) |
| Dropped() | Returns a read-only channel for events dropped because the main Events() channel was full |
Logging
FSWatcher includes a built-in structured logger to help with debugging and monitoring. You can control the verbosity and output destination using WatcherOpt functions.
Log Severity
| Level | Description |
| :--- | :--- |
| SeverityNone | No messages logged |
| SeverityError | 🚨 Only critical errors (e.g., platform failures) |
| SeverityWarn | ⚠️ Errors and warnings (e.g., event queue overflows) — default |
| SeverityInfo | ℹ️ Errors, warnings, and informational messages (e.g., watcher start/stop, paths added/removed) |
| SeverityDebug | 🐛 Everything, including detailed event processing steps (raw events, filtering, debouncing) |
Workflow
The watcher operates in a clear, multi-stage pipeline. Each raw OS event goes through:
| Stage | Description |
| :--- | :--- |
| OS API | The OS (FSEvents, inotify, ReadDirectoryChangesW) captures a raw file system event |
| Filtering | The path is checked against system file rules and regex patterns. Excluded paths are dropped |
| Debouncing | The event is held for the cooldown period. Subsequent events for the same path are merged. The timer resets on each new event |
| User channel | The final, clean WatchEvent is sent to Events() |
Event Aggregation
FSWatcher uses an EventAggregator to handle the noise of many OS events. For example, when you save a file, the OS might emit multiple "Edit" and "Chmod" events in rapid succession.
The EventAggregator works by:
- Deduplication — multiple events for the same path within the cooldown window are merged
- Type collection — the final
WatchEventcontains all uniqueEventTypevalues (e.g., bothCreateandEditif both occurred) - Flag collection — all platform-specific flags are collected and merged
- Deterministic ordering — aggregated
Typesare sorted by enum order andFlagsare sorted
