| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108 |
- const { contextBridge, ipcRenderer } = require('electron');
- const path = require('path');
- const os = require('os');
- const fs = require('fs');
- /**
- * 文件操作相关的预加载脚本
- */
- contextBridge.exposeInMainWorld('fileAPI', {
- /**
- * 使用 7z 压缩文件
- * @param {Object} opts 压缩选项
- * @returns {Promise} 压缩结果
- */
- compress: (opts) => ipcRenderer.invoke('compress-with-7z', opts),
- /**
- * 监听压缩进度
- * @param {Function} cb 回调函数,接收进度文本作为参数
- * @returns {Function} 用于移除监听器的函数
- */
- onProgress: (cb) => {
- const handler = (event, data) => cb(String(data));
- ipcRenderer.on('compress-progress', handler);
- return () => ipcRenderer.removeListener('compress-progress', handler);
- },
- /**
- * 监听压缩错误输出
- * @param {Function} cb 回调函数,接收错误文本作为参数
- * @returns {Function} 用于移除监听器的函数
- */
- onStderr: (cb) => {
- const handler = (event, data) => cb(String(data));
- ipcRenderer.on('compress-stderr', handler);
- return () => ipcRenderer.removeListener('compress-stderr', handler);
- },
- /**
- * 删除临时解压目录
- * @param {string} tmpDir 临时解压目录路径
- */
- deleteTempDir: (tmpDir) => {
- return fs.rmSync(tmpDir, { recursive: true, force: true });
- },
- /**
- * 创建临时文件夹
- * @param {string} prefix 临时文件夹前缀
- * @returns {string} 创建的临时文件夹路径
- */
- createTempDir: (prefix) => {
- const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), prefix || 'eep-'));
- const dirResourcePath = path.join(tmpDir, 'resource');
- if (!fs.existsSync(dirResourcePath)) {
- fs.mkdirSync(dirResourcePath);
- }
- const dirCoursewarePath = path.join(tmpDir, 'courseware');
- if (!fs.existsSync(dirCoursewarePath)) {
- fs.mkdirSync(dirCoursewarePath);
- }
- return tmpDir;
- },
- /**
- * 读取解压后的文件内容
- * @param {string} tmpDir 临时解压目录路径
- * @param {string} entryName 文件条目名称
- * @returns {Buffer} 文件内容
- */
- readZipFileSync: (tmpDir, entryName) => {
- const filePath = path.join(tmpDir, entryName);
- return fs.readFileSync(filePath);
- },
- /**
- * 下载文件
- * @param {string} url 文件 URL
- * @param {string} destPath 保存路径
- */
- downloadFile: (url, destPath) => {
- return ipcRenderer.invoke('download-file', { url, destPath });
- },
- /**
- * 打开文件对话框
- * @param {Object} opts 对话框选项
- * @returns {Promise} 文件路径
- */
- openFileDialog: (opts) => ipcRenderer.invoke('dialog:openFiles', opts),
- /**
- * 检查文件路径是否存在
- * @param {string} filePath 文件路径
- * @returns {boolean} 是否存在
- */
- existsSync: (filePath) => fs.existsSync(filePath),
- /**
- * 创建目录(递归)
- * @param {string} dirPath 目录路径
- */
- mkdirSync: (dirPath) => {
- if (!fs.existsSync(dirPath)) {
- fs.mkdirSync(dirPath, { recursive: true });
- }
- },
- });
|