Electron框架使用vue开发跨平台桌面工具应用-后台日志发送到前台和执行导入ZIP

一、后台日志发送到前台

  1. 首先在preload.js里面注册回调
    image
  2. 因为需要主窗口给vue页面发送,需要把窗口管理起来,不能直接写在backgroud.js里面。需要暴露出来所以编写了windowManager.js
// windowManager.js
let mainWindow = null;

// 设置 mainWindow
export function setMainWindow(window) {
  mainWindow = window;
}

// 获取 mainWindow
export function getMainWindow() {
  return mainWindow;
}

// 发送日志到渲染进程
export function sendLog(message) {
  if (mainWindow) {
    mainWindow.webContents.send('sql-log', message);
  } else {
    console.error('Main window not initialized.');
  }
}

backgroud.js里面引用,并 setMainWindow(win);
3.在vue的js里面调用 sendLog("日志信息")

二、执行导入sql然后删除

  1. 解压不能使用_dirname了而是path(_dirname)获取到运行目录,也可以使用process.execpath获取执行exe所在的目录
 // 解压 ZIP 文件
        const zip = new AdmZip(zipfile);
        //const tempDir = path.join(__dirname, 'temp');
        //sendLog(process.execPath);
        //const tempDir = path.join(path.dirname(process.execPath), 'temp');
        const tempDir = path.join(path.dirname(__dirname), 'temp');
        if (!fs.existsSync(tempDir)) {
          fs.mkdirSync(tempDir);
        }
        zip.extractAllTo(tempDir, true);
  1. 删除函数如下
  async function deleteTempDirectory(dirPath) {
    try {
      const files = fs.readdirSync(dirPath);
      
      // 删除目录中的所有文件
      for (const file of files) {
        const filePath = path.join(dirPath, file);
        const stat = fs.statSync(filePath);
  
        if (stat.isDirectory()) {
          // 如果是目录,递归删除
          await deleteTempDirectory(filePath);
        } else {
          // 如果是文件,直接删除
          fs.unlinkSync(filePath);
        }
      }
  
      // 删除空目录
      fs.rmdirSync(dirPath);
      console.log(`临时文件夹 ${dirPath} 已删除`);
    } catch (error) {
      console.error('删除临时文件夹时发生错误:', error);
    }
  }
posted @ 2024-11-18 13:53  lovefoolself  阅读(127)  评论(0)    收藏  举报