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

javascript
// 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.');
}
}
javascript
// 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然后删除
ini
// 解压 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);
ini
// 解压 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);
javascript
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);
}
}
javascript
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);
}
}