plus-io.uts 5.63 KB
/* eslint-disable unicorn/text-encoding-identifier-case */
/**
 * plus.io 的 uni-app x 替代实现
 * 用于文件系统操作
 */

import { get } from "./common.uts";

/**
 * 获取文件路径(私有文档目录)
 */
export function getFilePath(): Promise<string> {
	return new Promise((resolve, reject) => {
		// #ifdef APP
		// App 端:uni-app x 中,使用相对路径时 uni.getFileSystemManager 会自动解析到应用私有目录
		// 或者直接使用 uni.env.USER_DATA_PATH(但需要避免类型推断问题)
		// 这里使用相对路径 "files" 目录,系统会自动映射到私有目录
		const userDataPath = "files";
		resolve(userDataPath);
		// #endif

		// #ifndef APP
		// H5 和小程序使用临时路径
		resolve("/tmp");
		// #endif
	});
}

/**
 * 检查文件是否存在
 * @param filePath 文件路径
 */
export function checkFileExists(filePath: string): Promise<boolean> {
	return new Promise((resolve) => {
		// #ifdef APP
		const fs = uni.getFileSystemManager();
		fs.access({
			path: filePath,
			success: () => {
				resolve(true);
			},
			fail: () => {
				resolve(false);
			}
		});
		// #endif

		// #ifndef APP
		// H5 无法直接检查文件,假设存在
		resolve(true);
		// #endif
	});
}

/**
 * 读取文件
 * @param filePath 文件路径
 * @param encoding 编码格式,默认 'utf-8'
 */
export function readFile(filePath: string, encoding: string = "utf-8"): Promise<string> {
	return new Promise((resolve, reject) => {
		const fs = uni.getFileSystemManager();
		fs.readFile({
			filePath,
			encoding,
			success: (res: any) => {
				// ReadFileSuccessResult 类型,data 类型为 string | ArrayBuffer
				// 由于 ReadFileSuccessResult 不是 UTSJSONObject,需要特殊处理
				let text = "";
				let raw: any | null = null;

				// 方法1:尝试使用 JSON.parseObject(返回 UTSJSONObject)
				try {
					const jsonStr = JSON.stringify(res);

					const parsed = JSON.parseObject(jsonStr);

					if (parsed != null) {
						const temp = parsed.getAny("data");
						raw = temp != null ? temp as any : null;
					}
				} catch {

					// 方法2:如果 parseObject 失败,尝试用普通 parse
					try {
						const jsonStr = JSON.stringify(res);
						const parsed = JSON.parse(jsonStr);

						// 尝试从解析后的对象中获取 data
						if (parsed != null) {
							const temp = get(parsed as UTSJSONObject, "data");
							raw = temp != null ? temp as any : null;
						}
					} catch (error: any) {
						console.error("readFile method2 failed:", error);
					}
				}

				if (raw != null) {
					if (typeof raw === "string") {
						text = raw as string;
					} else {
						// ArrayBuffer 类型,需要转换为字符串
						// #ifdef APP
						// App 端:ArrayBuffer 转字符串
						// 对于 utf-8 编码,可以直接使用 TextDecoder
						try {
							const decoder = new TextDecoder("utf-8");
							text = decoder.decode(raw as ArrayBuffer);
						} catch (error: any) {
							console.error("ArrayBuffer decode error:", error);
							text = "";
						}
						// #endif
						// #ifndef APP
						// H5 等其他平台
						text = `${raw}`;
						// #endif
					}
				}
				resolve(text);
			},
			fail: (err: any) => {
				console.error("readFile fail:", err);
				reject(err);
			}
		});
	});
}

/**
 * 写入文件
 * @param filePath 文件路径
 * @param data 要写入的数据
 */
export function writeFile(filePath: string, data: string): Promise<void> {
	return new Promise((resolve, reject) => {
		const fs = uni.getFileSystemManager();
		fs.writeFile({
			filePath,
			data,
			encoding: "utf-8",
			success: () => {
				resolve();
			},
			fail: (err: any) => {
				reject(err);
			}
		});
	});
}

/**
 * 删除文件
 * @param filePath 文件路径
 */
export function deleteFile(filePath: string): Promise<void> {
	return new Promise((resolve, reject) => {
		const fs = uni.getFileSystemManager();
		fs.unlink({
			filePath,
			success: () => {
				resolve();
			},
			fail: (err: any) => {
				reject(err);
			}
		});
	});
}

/**
 * 读取目录内容
 * @param dirPath 目录路径
 */
export function readDirectory(dirPath: string): Promise<string[]> {
	return new Promise((resolve, reject) => {
		const fs = uni.getFileSystemManager();
		fs.readdir({
			dirPath,
			success: (res: any) => {
				let fileList: any | null = null;
				try {
					const jsonStr = JSON.stringify(res);
					const parsed = JSON.parseObject(jsonStr);
					if (parsed != null) {
						fileList = parsed.getAny("files");
					}
				} catch {
					try {
						const jsonStr = JSON.stringify(res);
						const parsed = JSON.parse(jsonStr);
						if (parsed != null) {
							fileList = get(parsed as UTSJSONObject, "files");
						}
					} catch {}
				}
				resolve(Array.isArray(fileList) ? fileList as string[] : []);
			},
			fail: (err: any) => {
				reject(err);
			}
		});
	});
}

/**
 * 创建目录
 * @param dirPath 目录路径
 * @param recursive 是否递归创建,默认 false
 */
export function createDirectory(dirPath: string, recursive: boolean = false): Promise<void> {
	return new Promise((resolve, reject) => {
		const fs = uni.getFileSystemManager();
		fs.mkdir({
			dirPath,
			recursive,
			success: () => {
				resolve();
			},
			fail: (err: any) => {
				reject(err);
			}
		});
	});
}

/**
 * 删除目录
 * @param dirPath 目录路径
 * @param recursive 是否递归删除,默认 false
 */
export function deleteDirectory(dirPath: string, recursive: boolean = false): Promise<void> {
	return new Promise((resolve, reject) => {
		const fs = uni.getFileSystemManager();
		fs.rmdir({
			dirPath,
			recursive,
			success: () => {
				resolve();
			},
			fail: (err: any) => {
				reject(err);
			}
		});
	});
}