因为工作原因,需要实现一款让用户下载了exe,安装后,打开可视化界面即可自动启动java web服务,并将请求到首页的应用。
const { contextBridge } = require('electron')
const { spawn, exec } = require('child_process')
const path = require('path')
contextBridge.exposeInMainWorld('myAPI', {
startServerForSpawn: () => {
let path1 = path.join(__dirname, 'app/ruoyi-admin.jar');
const ls = spawn('java', ['-jar', path1]);
ls.stdout.on('data', (data) => {
if(data.toString().indexOf("Started RuoYiApplication") !== -1){
window.location.href="http://localhost:80";
}
});
ls.stderr.on('data', (data) => {
console.error(`stderr: ${data}`);
alert("启动服务异常");
});
ls.on('close', (code) => {
console.log(`child process exited with code ${code}`);
});
},
startServerForbat: () =>{
const bat = spawn(path.join(__dirname, 'my.bat'));
bat.stdout.on('data', (data) => {
console.log(data.toString());
if(data.toString().indexOf("Started RuoYiApplication") !== -1){
window.location.href="http://localhost:80";
}
});
bat.stderr.on('data', (data) => {
console.error(data.toString());
});
bat.on('exit', (code) => {
console.log(`Child exited with code ${code}`);
});
}
})
DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>loadingtitle>
head>
<body>
<h1>Loadingh1>
<div>正在启动,请等待!div>
<script>
window.myAPI.startServerForbat();
console.log("-----------hello-------------")
script>
body>
html>
cd ./jre/bin
java -jar ../../app/ruoyi-admin.jar
DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="Content-Security-Policy" content="">
<title>indextitle>
head>
<body>
<script src="./static/js/jquery.min.js"> script>
<script>
$(document).ready(function(){
$.ajax({
timeout: 200,
type: 'GET',
url: 'http://localhost',
data: {
},
success: function(obj){
window.location.href = "http://localhost"
},
error: function(obj){
window.location.href = "loading.html";
}
})
})
script>
body>
html>
{
"name": "electron-quick-start",
"version": "1.0.0",
"description": "A minimal Electron application",
"main": "main.js",
"scripts": {
"start": "electron .",
"package": "electron-packager . construction --win --out build --arch=x64 --version1.0.0 --overwrite --icon=static/images/128.ico",
"dist": "electron-builder --win --x64",
"win32": "electron-builder --win --ia32"
},
"repository": "https://github.com/electron/electron-quick-start",
"keywords": [
"Electron",
"quick",
"start",
"tutorial",
"demo"
],
"author": "GitHub",
"license": "CC0-1.0",
"devDependencies": {
"electron": "^14.0.0"
},
"build": {
"appId": "com.phil.test",
"copyright": "https://github.com/phil-cheng",
"productName": "java打包",
"asar": false,
"mac": {
"target": [
"dmg",
"zip"
]
},
"win": {
"target": [
"nsis",
"zip"
],
"icon": "static/images/256.ico"
}
}
}
因为第一次上述配置里"asar"默认为true,所以打包会把应用下的代码打包成一个归档文件-asar,如图右边,这就会导致程序在执行bat脚本时找不到本地文件。
asar严格意义上也不是对代码加密,只是类似于zip一样做了归档处理,通过其对应的命令是可以“解压”出来的
解决办法有两个:
"extraResources": { //把需要访问的文件移动到外层目录
"from": "template",
"to": "temp"
},