How do you dynamically observe files in a directory and log a new file as it appears
trookie2000 opened this issue · 1 comments
trookie2000 commented
I'm new to rust, and the feature I want to implement is to watch the folder under "D:/ working directory /tools" and whenever a new file appears, return a line of text to the front-end textarea with id=log_content.
But my code is not doing my job correctly. It just outputs a log line when the program runs. How can I change that?
(The backend uses rust+tauri,Front-end html+css+js)
The code is as follows:
1.The get_log function:
2.discoroboy.html:
trookie2000 commented
get_log
#[command]
async fn get_log(id: i32) -> Option {
let content = fs::read_to_string("D:/code/rust/robot/src-tauri/src/config_file/ErrorTypeList.xml").expect("error");
let parser = EventReader::from_str(&content);
let mut is_parsing_log = false;
let mut log = String::new();
for e in parser {
match e {
Ok(XmlEvent::StartElement {
name, attributes, ..
}) => {
let element_name = name.local_name.to_string();
if element_name.starts_with("ErrorInfo4") {
is_parsing_log = true;
}
}
Ok(XmlEvent::EndElement { name }) => {
if is_parsing_log {
is_parsing_log = false;
log.push('\n');
}
}
Ok(XmlEvent::Characters(content)) => {
if is_parsing_log {
let current_time = Local::now();
let time_str = current_time.format("%Y-%m-%d %H:%M:%S").to_string();
log.push_str(&format!("[{}] {}\n", time_str, content));
let mut watcher = notify::recommended_watcher(|res| {
match res {
Ok(event) => println!("event: {:?}", event),
Err(e) => println!("watch error: {:?}", e),
}
}).ok()?;
let directory_path = "D:/工作目录/tools";
// Add a path to be watched. All files and directories at that path and
// below will be monitored for changes.
watcher
.watch(Path::new(directory_path), RecursiveMode::Recursive)
.ok()?;
}
}
_ => {}
}
}
Some(log)
}
discorobot.html
<textarea class="textarea" id="logContent"></textarea> invoke('get_log', { skillInfo: response, id: id })
.then((logResponse) => {
console.log('Log Response:', logResponse);
const logTextarea = document.getElementById("logContent");
logTextarea.readOnly = true;
logTextarea.value = logResponse;
})
.catch((error) => {
console.error('Error calling get_log:', error);
});