preload.js 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. const { contextBridge, ipcRenderer } = require('electron');
  2. const path = require('path');
  3. const os = require('os');
  4. const fs = require('fs');
  5. /**
  6. * 文件操作相关的预加载脚本
  7. */
  8. contextBridge.exposeInMainWorld('fileAPI', {
  9. /**
  10. * 使用 7z 压缩文件
  11. * @param {Object} opts 压缩选项
  12. * @returns {Promise} 压缩结果
  13. */
  14. compress: (opts) => ipcRenderer.invoke('compress-with-7z', opts),
  15. /**
  16. * 监听压缩进度
  17. * @param {Function} cb 回调函数,接收进度文本作为参数
  18. * @returns {Function} 用于移除监听器的函数
  19. */
  20. onProgress: (cb) => {
  21. const handler = (event, data) => cb(String(data));
  22. ipcRenderer.on('compress-progress', handler);
  23. return () => ipcRenderer.removeListener('compress-progress', handler);
  24. },
  25. /**
  26. * 监听压缩错误输出
  27. * @param {Function} cb 回调函数,接收错误文本作为参数
  28. * @returns {Function} 用于移除监听器的函数
  29. */
  30. onStderr: (cb) => {
  31. const handler = (event, data) => cb(String(data));
  32. ipcRenderer.on('compress-stderr', handler);
  33. return () => ipcRenderer.removeListener('compress-stderr', handler);
  34. },
  35. /**
  36. * 删除临时解压目录
  37. * @param {string} tmpDir 临时解压目录路径
  38. */
  39. deleteTempDir: (tmpDir) => {
  40. return fs.rmSync(tmpDir, { recursive: true, force: true });
  41. },
  42. /**
  43. * 创建临时文件夹
  44. * @param {string} prefix 临时文件夹前缀
  45. * @returns {string} 创建的临时文件夹路径
  46. */
  47. createTempDir: (prefix) => {
  48. const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), prefix || 'eep-'));
  49. const dirResourcePath = path.join(tmpDir, 'resource');
  50. if (!fs.existsSync(dirResourcePath)) {
  51. fs.mkdirSync(dirResourcePath);
  52. }
  53. const dirCoursewarePath = path.join(tmpDir, 'courseware');
  54. if (!fs.existsSync(dirCoursewarePath)) {
  55. fs.mkdirSync(dirCoursewarePath);
  56. }
  57. return tmpDir;
  58. },
  59. /**
  60. * 读取解压后的文件内容
  61. * @param {string} tmpDir 临时解压目录路径
  62. * @param {string} entryName 文件条目名称
  63. * @returns {Buffer} 文件内容
  64. */
  65. readZipFileSync: (tmpDir, entryName) => {
  66. const filePath = path.join(tmpDir, entryName);
  67. return fs.readFileSync(filePath);
  68. },
  69. /**
  70. * 下载文件
  71. * @param {string} url 文件 URL
  72. * @param {string} destPath 保存路径
  73. */
  74. downloadFile: (url, destPath) => {
  75. return ipcRenderer.invoke('download-file', { url, destPath });
  76. },
  77. /**
  78. * 打开文件对话框
  79. * @param {Object} opts 对话框选项
  80. * @returns {Promise} 文件路径
  81. */
  82. openFileDialog: (opts) => ipcRenderer.invoke('dialog:openFiles', opts),
  83. });