Skip to content

Instantly share code, notes, and snippets.

@lalizita
Last active April 8, 2023 17:31
Show Gist options
  • Save lalizita/dc81b30fc7b9b5af4d0d2d133b32c6e6 to your computer and use it in GitHub Desktop.
Save lalizita/dc81b30fc7b9b5af4d0d2d133b32c6e6 to your computer and use it in GitHub Desktop.
Watch file changes inside a directory
package main
import (
"fmt"
"io/fs"
"log"
"os"
"path/filepath"
"github.com/fsnotify/fsnotify"
)
func main() {
fileUpdated := make(chan string)
go WatchEvents(fileUpdated)
for f := range fileUpdated {
fmt.Println("File updated:", f)
}
}
//Create watcher event function that receives a channel to receive the current file changed
func WatchEvents(updateF chan<- string) {
//Create a watcher to listen system events
watcher, err := fsnotify.NewWatcher()
if err != nil {
log.Fatal(err)
}
//Mount directory path to watch, you can edit it
path, _ := os.Getwd()
directories := fmt.Sprintf("%s/root", path)
//Use filepath to iterate in every file inside a directory
err = filepath.WalkDir(directories, func(pathDir string, d fs.DirEntry, err error) error {
if err != nil {
log.Fatal(err)
return err
}
if d.IsDir() {
//Add file to watcher list
err = watcher.Add(pathDir)
if err != nil {
log.Fatal(err)
}
}
return nil
})
if err != nil {
log.Fatal("Error in file path:", err.Error())
}
//Iterate over the Events channel to validate when a Write event occours
for event := range watcher.Events {
if event.Has(fsnotify.Write) {
//insert the filename in the channel received when we create this function
updateF <- event.Name
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment