preload.js 2.7 KB

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