#tokio #watch #file #async #serde #serde-derive #read-file

watchfile

An async utility trait to subscribe to file changes of a serializable file

2 releases

0.1.1 Nov 18, 2024
0.1.0 Nov 18, 2024

#661 in Filesystem

Download history 228/week @ 2024-11-15 40/week @ 2024-11-22 20/week @ 2024-11-29 16/week @ 2024-12-06

304 downloads per month

MIT license

20KB
195 lines

Watchfile

A simple trait that will watch a (serializable) file for changes and update a data struct.

Uses tokio for async file reading and tokio::sync::watch for notifying about changes.

File types / Features

Currently supported:

  • JSON (features = ["json"] using serde_json)
  • TOML (features = ["toml"] using toml)
  • YAML (features = ["yaml"] using serde_yaml)

All of them are optional features, all enabled by default. To minimize dependencies, you can disable them by using default-features = false in your Cargo.toml, and then enabling only the ones you need (for example, only JSON):

[dependencies]
watchfile = { version = "0.1", default-features = false, features = ["json"] }

Usage:

use std::time::Duration;
use watchfile::WatchFile;
use std::ops::Deref;

#[derive(serde::Deserialize, Default, PartialEq, Debug)]
struct Config {
  data: String,
}

impl WatchFile for Config {}

#[tokio::main]
async fn main() {
  let rx = Config::watch_file("config.json", Duration::from_secs(1));
  assert_eq!(rx.borrow().deref(), &Config::default());
}

Dependencies

~2.7–8.5MB
~73K SLoC