Rabarar's Blog

A blogging framework for mild hackers.

Spying on Files With Fsnotify

| Comments

Sometimes you want to automate a workflow process by watching a filesystem directory and treating it like a work queue. As files arrive in the directory, a process watching the directory can be notified of new work items and kick off a process to perform the desired task.

A golang package called fsnotify does most of the nitty-gritty to make the details of implementing a queue manager somewhat trivial. Below is an example of how you would set up a queue to watch a directory using the package:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
   package main

  import (
      "log"

      "github.com/go-fsnotify/fsnotify"
  )

  func main() {

      watcher, err := fsnotify.NewWatcher()
      if err != nil {
          log.Fatal(err)
      }
      defer watcher.Close()

      done := make(chan bool)
      go func() {
          for {
              select {
              case event := <-watcher.Events:
                  log.Println("event:", event)
                  if event.Op&fsnotify.Write == fsnotify.Write {
                      log.Println("modified file:", event.Name)
                  }
              case err := <-watcher.Errors:
                  log.Println("error:", err)
              }
          }
      }()

      err = watcher.Add("/tmp/foo")
      if err != nil {
          log.Fatal(err)
      }
      <-done
  }

In the main of the golang program, we create a new watcher and start a go-routine that selects events from the watcher Events channel. Each event is logged and then if an event of type ‘fsnotiy.Write’ is received by the watcher, an additional log message is printed. Outside of the go-routine, we add the /tmp/foo directory to the watcher and wait on the done channel (which will block indefinitely).

Comments