Grav v1.14.0

Watch

import "std/io" (included in import "std") · namespace std.io

FileWatcher reports which files under some paths were created, changed or deleted. A thread looks every intervalMs (500 by default) and compares each file's modification time, to the nanosecond, and size with the last look. That works the same on every system and file system, network mounts and containers included. Between looks it only sleeps, and it keeps one small entry per file. Names in ignore (.git, node_modules, build, target to begin with) are skipped under a watched directory.

grav
import "std"

fn main() {
    let dir = Dir.temp() + "/watch_demo"
    Dir.removeAll(dir)
    Dir.create(dir)
    let w = new FileWatcher([dir], 100)
    w.poll()                                       // the starting point
    new File(dir + "/notes.txt").write("hello")
    for (c in w.poll()) { print("${c.kind} ${Path.basename(c.path)}") }

    let seen = new AtomicInt(0)
    w.start(fn(changes: Array<FileChange>) { seen.add(changes.size()) })   // on a thread
    new File(dir + "/notes.txt").delete()
    while (seen.get() == 0) { Thread.sleepMs(20) }
    w.stop()
    print(seen.get())
    Dir.removeAll(dir)
}
Output
created notes.txt
1

class FileChange

One change: "created", "modified" or "deleted", and the file's path.

Constructors

  • new FileChange(kind: string, path: string)

Fields

  • kind: string
  • path: string

class FileStamp

What a watcher saw of a file the last time.

Constructors

  • new FileStamp(mtime: long, size: long)

Fields

  • mtime: long
  • size: long

class FileWatcher

Constructors

  • new FileWatcher(paths: Array<string>, intervalMs: int = 500)

Fields

  • paths: Array<string> — The files and directories watched (directories with everything under them).
  • intervalMs: int — How long (ms) between looks.
  • ignore: Array<string> = [".git", "node_modules", "build", "target"] — Names under a watched directory left out (exact names, such as ".git" or "build").

Methods

  • fn start(onChange: fn(Array<FileChange>)) — Watches on a thread of its own, calling onChange with each look's changes (never with none). The files there now are the starting point.
  • fn stop() — Stops watching (and waits for the thread).
  • fn poll() -> Array<FileChange> — Looks once: what changed since the last look (the first look reports nothing).

Edit this page on GitHub