How to watch for file/directory changes in Rust and how to integrate this in a non-blocking way? The canonical example (such as that provided by https://docs.rs/notify/4.0.15/notify/), shows how to watch the files, but it will block the rest of your main function execution. (I'm pursuing this https://doc.rust-lang.org/std/sync/mpsc/fn.channel.html)
The example code for the notify
crate does what you want. It uses RecursiveMode::Recursive
to specify to watch all files and subdirectories within the provided path.
use notify::{Watcher, RecursiveMode, watcher};
use std::sync::mpsc::channel;
use std::time::Duration;
fn main() {
// Create a channel to receive the events.
let (sender, receiver) = channel();
// Create a watcher object, delivering debounced events.
// The notification back-end is selected based on the platform.
let mut watcher = watcher(sender, Duration::from_secs(10)).unwrap();
// Add a path to be watched. All files and directories at that path and
// below will be monitored for changes.
watcher.watch("/path/to/watch", RecursiveMode::Recursive).unwrap();
loop {
match receiver.recv() {
Ok(event) => println!("{:?}", event),
Err(e) => println!("watch error: {:?}", e),
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With