preload.js 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. const { contextBridge, ipcRenderer } = require('electron');
  2. const path = require('path');
  3. const fs = require('fs');
  4. const os = require('os');
  5. // 公开给渲染进程的 API
  6. contextBridge.exposeInMainWorld('fileAPI', {
  7. /**
  8. * 用主进程的 7z 解压(支持密码)
  9. * @param {string} filePath EEP 文件路径
  10. * @param {string} password 密码
  11. * @returns {Promise} 解压结果
  12. */
  13. extractZip: async (filePath, password = '') => {
  14. return await ipcRenderer.invoke('extract-zip', { filePath, password });
  15. },
  16. /**
  17. * 读取解压后的文件内容
  18. * @param {string} tempDir 临时解压目录路径
  19. * @param {string} entryName 文件条目名称
  20. * @returns {Buffer} 文件内容
  21. */
  22. readZipFileSync: (tempDir, entryName) => {
  23. const filePath = path.join(tempDir, entryName);
  24. return fs.readFileSync(filePath);
  25. },
  26. /**
  27. * 读取解压后的目录内容
  28. * @param {string} tempDir 临时解压目录路径
  29. * @param {string} entryName 目录条目名称
  30. * @returns {string[]} 目录下的文件和子目录列表
  31. */
  32. readZipDirSync: (tempDir, entryName) => {
  33. const dirPath = path.join(tempDir, entryName);
  34. return fs.readdirSync(dirPath);
  35. },
  36. /**
  37. * 删除临时解压目录
  38. * @param {string} tempDir 临时解压目录路径
  39. */
  40. deleteTempDir: (tempDir) => {
  41. fs.rmSync(tempDir, { recursive: true, force: true });
  42. },
  43. /**
  44. * 监听主进程发送的打开 EEP 文件事件
  45. * @param {Function} callback 回调函数,接收文件路径作为参数
  46. * @returns {Function} 用于移除监听器的函数
  47. */
  48. onOpenEep: (callback) => {
  49. const handler = (event, filePath) => callback(filePath);
  50. ipcRenderer.on('open-eep', handler);
  51. return () => ipcRenderer.removeListener('open-eep', handler);
  52. },
  53. /**
  54. * 修改 .eep 压缩文件中的某个文件内容
  55. * @param {string} archivePath EEP 文件路径
  56. * @param {string} entryPath 压缩包内文件路径
  57. * @param {Buffer} content 新文件内容
  58. */
  59. modifyEepFileSync: async (archivePath, entryPath, content, encoding = 'utf8', password = '') => {
  60. return await ipcRenderer.invoke('zip:update-entry-with-7z', {
  61. archivePath,
  62. entryPath,
  63. content,
  64. encoding,
  65. password,
  66. });
  67. },
  68. /**
  69. * 打开文件对话框
  70. * @param {Object} opts 对话框选项
  71. * @returns {Promise} 文件路径
  72. */
  73. openFileDialog: (opts) => ipcRenderer.invoke('dialog:openFiles', opts),
  74. });
  75. // 简单的键值存储 API
  76. contextBridge.exposeInMainWorld('electronStore', {
  77. get: (key) => ipcRenderer.invoke('store:get', key),
  78. set: (key, value) => ipcRenderer.invoke('store:set', key, value),
  79. delete: (key) => ipcRenderer.invoke('store:delete', key),
  80. });
  81. // 系统信息 API
  82. contextBridge.exposeInMainWorld('systemAPI', {
  83. getSystemInfo: () => ({
  84. platform: os.platform(),
  85. arch: os.arch(),
  86. }),
  87. });