vanadin_tasks/modules/
fs.rs1use std::fs;
2
3use rquickjs::module::{Declarations, Exports, ModuleDef};
4use rquickjs::{Ctx, Function};
5
6pub struct Module;
7
8impl ModuleDef for Module {
9 #[inline(always)]
10 fn declare(declarations: &mut Declarations) -> rquickjs::Result<()> {
11 declarations.declare("readFile")?;
12 declarations.declare("writeFile")?;
13 declarations.declare("readFileBytes")?;
14 declarations.declare("writeFileBytes")?;
15 declarations.declare("createFile")?;
16 declarations.declare("removeFile")?;
17 declarations.declare("createDir")?;
18 declarations.declare("removeDir")?;
19 declarations.declare("exists")?;
20
21 Ok(())
22 }
23
24 #[inline(always)]
25 fn evaluate<'js>(ctx: &Ctx<'js>, exports: &mut Exports<'js>) -> rquickjs::Result<()> {
26 exports.export("readFile", Function::new(ctx.clone(), Self::read_file))?;
27 exports.export("writeFile", Function::new(ctx.clone(), Self::write_file))?;
28 exports.export(
29 "readFileBytes",
30 Function::new(ctx.clone(), Self::read_file_bytes),
31 )?;
32 exports.export(
33 "writeFileBytes",
34 Function::new(ctx.clone(), Self::write_file_bytes),
35 )?;
36 exports.export("createFile", Function::new(ctx.clone(), Self::create_file))?;
37 exports.export("removeFile", Function::new(ctx.clone(), Self::delete_file))?;
38 exports.export("createDir", Function::new(ctx.clone(), Self::create_dir))?;
39 exports.export("removeDir", Function::new(ctx.clone(), Self::delete_dir))?;
40 exports.export("exists", Function::new(ctx.clone(), Self::exists))?;
41
42 Ok(())
43 }
44}
45
46impl Module {
47 fn read_file(path: String) -> Option<String> {
48 fs::read_to_string(path).ok()
49 }
50
51 fn write_file(path: String, content: String) {
52 fs::write(path, content).expect("Failed writing file");
53 }
54
55 fn read_file_bytes(path: String) -> Option<Vec<u8>> {
56 fs::read(path).ok()
57 }
58
59 fn write_file_bytes(path: String, content: Vec<u8>) {
60 fs::write(path, content).expect("Failed writing file");
61 }
62
63 fn create_file(path: String) {
64 fs::File::create(path).expect("Failed creating file");
65 }
66
67 fn delete_file(path: String) {
68 fs::remove_file(path).expect("Failed deleting file");
69 }
70
71 fn create_dir(path: String) {
72 fs::create_dir(path).expect("Failed creating dir");
73 }
74
75 fn delete_dir(path: String) {
76 fs::remove_dir(path).expect("Failed deleting dir");
77 }
78
79 fn exists(path: String) -> bool {
80 fs::metadata(path).is_ok()
81 }
82}