📚Cheatsheets

Cheatsheet collection for go, rust and javascript.

Detect file changes

Watch file changes with inotify.

Cargo.toml

[dependencies]
notify = "4"

Code:

extern crate notify;
use notify::{DebouncedEvent, RecommendedWatcher, RecursiveMode, Watcher};
use std::sync::mpsc::channel;
use std::time::Duration;
use std::path::Path;

fn watch(file_path: &str) -> notify::Result<()> {
    let (tx, rx) = channel();
    let delay = 300;
    let mut watcher: RecommendedWatcher = Watcher::new(tx, Duration::from_millis(delay))?;
    watcher.watch(Path::new(&file_path), RecursiveMode::NonRecursive)?;

    loop {
        let event = match rx.recv() {
            Ok(event) => event,
            Err(err) => {
                println!("Config watcher channel dropped unexpectedly: {}", err);
                break;
            }
        };

        match event {
            DebouncedEvent::Rename(_, path)
            | DebouncedEvent::Write(path)
            | DebouncedEvent::Create(path)
            | DebouncedEvent::Chmod(path) => {
                // do with file changes
            }
            _ => (),
        }
    }
    Ok(())
}