使用fsnotify监视现有文件

huangapple go评论79阅读模式
英文:

Monitoring an existing file with fsnotify

问题

我正在尝试使用golang中的fsnotify包来监视文件。

我看到了一些类似这样的示例,我想知道这是否是使用fsnotify的最佳方式:

package main

import (
	"log"

	"github.com/howeyc/fsnotify"
)

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

	done := make(chan bool)

	// 处理事件
	go func() {
		for {
			select {
			case ev := <-watcher.Event:
				log.Println("event:", ev)
			case err := <-watcher.Error:
				log.Println("error:", err)
			}
		}
	}()

	err = watcher.Watch("testDir")
	if err != nil {
		log.Fatal(err)
	}

	<-done

	var get_info []string
	get_info = read_file(path_to_file)

	watcher.Close()
}

基本上,我传递了文件所在的路径,并将结果存储在一个字符串变量中。

每当我更改文件时,我想读取文件并获取结果。

根据这个示例,我不确定我是否正确地使用了fsnotify。而且,我不确定在fsnotify中应该将文件路径放在哪里以监视该文件。

英文:

I'm trying to monitor a file using the fsnotify packet in golang.

I saw few examples like this and I would like to know if this is the best way of using fsnotify:

package main

import (
	&quot;log&quot;

	&quot;github.com/howeyc/fsnotify&quot;
)

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

	done := make(chan bool)

	// Process events
	go func() {
		for {
			select {
			case ev := &lt;-watcher.Event:
				log.Println(&quot;event:&quot;, ev)
			case err := &lt;-watcher.Error:
				log.Println(&quot;error:&quot;, err)
			}
		}
	}()

	err = watcher.Watch(&quot;testDir&quot;)
	if err != nil {
		log.Fatal(err)
	}

	&lt;-done

	var get_info := []string
    get_info = read_file(path_to_file) 


	watcher.Close()
}

Basically I'm passing a path where the file is located and geting the resul in a string variable.

Everytime I change the file I would like to read the file and get the result.

I'm not sure if I'm using fsnotify correctly base on that example. Also, I'm not sure where to put the file path in the fsnotify to monitor that file.

答案1

得分: 2

你基本上正确地利用了fsnotify,唯一的改变可能是你想要利用通道来获取事件,然后使用事件来提取更改的文件名。这样可以监视多个文件,并且在你的示例中,我不认为你曾经向done传递一个值,以便它能够正确地等待通道并读取文件内容。

我在下面添加了一个简单的示例,它去掉了go例程,只在主线程上监听更改。

func main() {
    watcher, err := fsnotify.NewWatcher()

    if err != nil {
            panic(err)
    }

    err = watcher.Add("file.txt")
    if err != nil {
            panic(err)
    }

    for {
            select {
            case ev := <-watcher.Events:
                    log.Println("event:", ev)
                    if ev.Op&fsnotify.Write == fsnotify.Write {
							contents, err := ioutil.ReadFile(ev.Name)
							if err != nil {
								// 处理错误
							}
							log.Println("modified file:", string(contents))
                    }
            case err := <-watcher.Errors:
                    log.Println("error:", err)
            }
    }
}
英文:

You're leveraging fsnotify pretty much correctly, the only change would likely be that you want to utilize the channel to grab events and then use the event to extract the file name that changed. This would allow you to monitor multiple files and also in your example I don't believe you ever pass a value into done for it to properly finish waiting on the channel and read the file contents.

I'm adding a simple sample below that gets rid of the go routine and simply listens for changes on the main thread.


func main() {
    watcher, err := fsnotify.NewWatcher()

    if err != nil {
            panic(err)
    }

    err = watcher.Add(&quot;file.txt&quot;)
    if err != nil {
            panic(err)
    }

    for {
            select {
            case ev := &lt;-watcher.Events:
                    log.Println(&quot;event:&quot;, ev)
                    if ev.Op&amp;fsnotify.Write == fsnotify.Write {
							contents, err := ioutil.ReadFile(ev.Name)
							if err != nil {
								// handle error
							}
							log.Println(&quot;modified file:&quot;, string(contents))
                    }
            case err := &lt;-watcher.Errors:
                    log.Println(&quot;error:&quot;, err)
            }
    }
}

huangapple
  • 本文由 发表于 2022年6月24日 16:58:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/72741501.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定