Home
Head's Up: I'm in the middle of upgrading my site. Most things are in place, but there are something missing and/or broken including image alt text. Please bear with me while I'm getting things fixed.

Watch A Directory For File Changes In Rust

See also : 2sg7pomp which uses _ full instead of _ mini which I've found to work better in some cases where you need to ignore access to files

I'm using [TODO: Code shorthand span ] in my Rust apps to watch directories for file changes.

A basic sample looks like this :

rust
use notify_debouncer_mini::{new_debouncer, notify::*};
use std::path::PathBuf;
use std::time::Duration;

fn main() {
    let _ = watch_files();
}


fn watch_files() -> Result<()> {
    let watch_dir = PathBuf::from(".");
    let (tx, rx) = std::sync::mpsc::channel();
    let mut debouncer = new_debouncer(Duration::from_millis(100), tx)?;
    debouncer
        .watcher()
        .watch(&watch_dir, RecursiveMode::Recursive)?;
    for result in rx {
        match result {
            Ok(events) => events.iter().for_each(|event| {
                dbg!(&event.path);
            }),
            Err(_) => {}
        }
    }
    Ok(())
}

- The "notify _ debouncer _ mini" crate filters incoming events and emits only one event per timeframe per file

- The Duration in this examples is milliseconds. If you set it two 2000 and change a file you'll see the notification 2 seconds later

- Sometimes it takes a little longer for things to register

- There's also "notify _ debouncer _ full" with more features including ones designed to prevent sending multiple events for renames. I don't need that for my use case

- This example uses and mpsc : : channel. Callbacks can be used as well

- Both _ mini and _ full ride on top of the overall notify crate which is a cross - platform file system notification library

Footnotes And References