The words Under construction in black text on a yellow background with diagonal black stipes surrounding it
I'm in the process of moving my site. It's still a work in progress. Please excuse the mess and broken links.

Watch A Directory For File Changes In Rust

TODO: Pull subtitle into page object
Code
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(())
}

Notes

Debugging Stuff

I'm moving stuff around right now. All this below is helping me figure out where to put stuff

        -- title

Watch A Directory For File Changes In Rust

I'm using `notify_debouncer_mini`` in my
Rust apps to watch directories for file changes. 

A basic sample looks like this:

-- code


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(())
}

-- notes

- 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


-- ref
-- url: https://docs.rs/notify-debouncer-mini/latest/notify_debouncer_mini/

-- ref
-- url: https://docs.rs/notify-debouncer-full/latest/notify_debouncer_full/

-- ref
-- url: https://docs.rs/notify/latest/notify/


-- categories
-- Rust 

-- metadata
-- date: 2023-09-05 00:26:10
-- id: 2uxj96li
-- site: aws
-- type: post
-- status: published