Skip to content

Commit

Permalink
feat: fs-extra 插件新增 exists 方法,并简化了代码
Browse files Browse the repository at this point in the history
  • Loading branch information
ayangweb committed Jun 14, 2024
1 parent 98a915b commit 098f195
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 12 deletions.
22 changes: 11 additions & 11 deletions src-tauri/src/fs_extra.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use serde::{ser::Serializer, Serialize};
use std::{fs, path::Path};
use std::{fs, path::PathBuf};
use tauri::{
command, generate_handler,
plugin::{Builder, TauriPlugin},
Expand Down Expand Up @@ -31,7 +31,7 @@ struct Metadata {
is_exist: bool,
}

fn get_dir_size<P: AsRef<Path>>(path: P) -> Result<u64> {
fn get_dir_size(path: PathBuf) -> Result<u64> {
let mut size = 0;

for entry in fs::read_dir(path)? {
Expand All @@ -49,16 +49,11 @@ fn get_dir_size<P: AsRef<Path>>(path: P) -> Result<u64> {
}

#[command]
async fn metadata(path: &str) -> Result<Metadata> {
let replace_path = path.replace("file://", "");

let path = Path::new(&replace_path);

let is_exist = path.exists();

async fn metadata(path: PathBuf) -> Result<Metadata> {
let mut size = 0;
let mut is_dir = false;
let mut is_file = false;
let is_exist = path.exists();

if is_exist {
let metadata = fs::metadata(&path)?;
Expand All @@ -69,7 +64,7 @@ async fn metadata(path: &str) -> Result<Metadata> {
size = if is_file {
metadata.len()
} else {
get_dir_size(&path)?
get_dir_size(path)?
};
}

Expand All @@ -81,8 +76,13 @@ async fn metadata(path: &str) -> Result<Metadata> {
})
}

#[command]
async fn exists(path: PathBuf) -> bool {
path.exists()
}

pub fn init() -> TauriPlugin<Wry> {
Builder::new("fs-extra")
.invoke_handler(generate_handler![metadata])
.invoke_handler(generate_handler![metadata, exists])
.build()
}
20 changes: 19 additions & 1 deletion src/utils/fsExtra.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,28 @@ interface Metadata {
isExist: boolean;
}

const handlePath = (path: string) => {
return decodeURI(path).replace("file://", "");
};

/**
* 获取系统文件(夹)的信息
* @param path 路径
*/
export const metadata = async (path: string) => {
const result = await invoke<any>("plugin:fs-extra|metadata", {
path: decodeURI(path),
path: handlePath(path),
});

return mapKeys(result, (_, key) => camelCase(key)) as Metadata;
};

/**
* 查看文件(夹)是否存在
* @param path 路径
*/
export const exists = async (path: string) => {
return await invoke<boolean>("plugin:fs-extra|exists", {
path: handlePath(path),
});
};

0 comments on commit 098f195

Please sign in to comment.