path-utils.uts
2.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
export class PathUtils {
static _basePath: string | null = null
// 默认保存文件夹名称
static SAVE_DIR_NAME = 'uniapp_save'
// 默认文件保存路径 (相对于 _doc/)
static DEFAULT_SAVE_PATH = "_doc/" + PathUtils.SAVE_DIR_NAME + "/"
static CACHED_ROOT_PATH: string | null = null
// 本地缓存键名
static ROOT_PATH_CACHE_KEY = 'sqlite_root_path_cache'
/**
* 路径拼接工具
* @param args 路径片段
* @returns
*/
static join(...args: string[]): string {
if (args.length == 0) return ''
const parts = args.map((part): string => {
if (part == "") return ''
let str = part
// 简单的去斜杠处理,UTS中正则可能需要注意
// 这里简化处理,假设输入相对规范
return str.trim()
}).filter((p: string): boolean => p.length > 0)
// 简单拼接,实际可能需要更复杂的逻辑处理 / 分隔符
return parts.join('/')
}
/**
* 获取基础保存路径 (带缓存)
*/
static async getBasePath(): Promise<string> {
if (PathUtils._basePath != null) return PathUtils._basePath!
PathUtils._basePath = await PathUtils.getFileSaveFolderOnClient()
return PathUtils._basePath!
}
/**
* 获取文件系统根目录的完整路径
* @returns {Promise<string>}
*/
static getFilePath(): Promise<string> {
// 1. 优先使用内存缓存,性能最高
if (PathUtils.CACHED_ROOT_PATH != null) {
// uni.$logger?.local?.info(`[PathUtils] 命中内存缓存,根路径: ${PathUtils.CACHED_ROOT_PATH}`);
return Promise.resolve(PathUtils.CACHED_ROOT_PATH!);
}
// 2. 尝试读取持久化缓存
const storageCache = uni.getStorageSync(PathUtils.ROOT_PATH_CACHE_KEY);
if (storageCache != null && storageCache != "") {
// uni.$logger?.local?.info(`[PathUtils] 命中本地缓存,根路径: ${storageCache}`);
// 同步到内存缓存
PathUtils.CACHED_ROOT_PATH = storageCache as string;
return Promise.resolve(PathUtils.CACHED_ROOT_PATH!);
}
// 3. 无缓存,请求原生文件系统API
return new Promise((resolve, reject) => {
// UTS 环境下优先使用 uni.env.USER_DATA_PATH
const userDataPath = uni.env.USER_DATA_PATH
PathUtils.CACHED_ROOT_PATH = userDataPath
uni.setStorageSync(PathUtils.ROOT_PATH_CACHE_KEY, userDataPath)
resolve(userDataPath)
});
}
/**
* 获取客户端文件保存基础路径
*/
static async getFileSaveFolderOnClient(): Promise<string> {
// 简单实现,直接调用 getFilePath
return await PathUtils.getFilePath()
}
}