让electron的渲染进程(vue)支持node环境,需要在main.js中,把nodeIntegration设为true
mainWindow = new BrowserWindow({
width: 1620,
height: 1080,
useContentSize: true,
// fullscreen: true, // 全屏
// frame: false, // 去掉菜单
webPreferences: {
nodeIntegration: true, // 使渲染进程拥有node环境
webSecurity: false
}
})
如果是electron-vue ,在vue中使用process.cwd()方法可以读取到打包后的根目录path,你可以把配置文件config.json放进根目录下,然后用fs.readFile读取。
let file = process.cwd() + 'config.json' // 文件路径
fs.readFile(file, 'utf-8', function (err, data) {
if (err) {
console.log(err)// eslint-disable-line
} else {
console.log(data)// eslint-disable-line
}
})
推荐这种做法,你可以不改任何代码,部署人员只需要在安装的目录下找这个文件修改即可,electron-builder工具可以拷贝静态资源,比如你把config.json放在项目的根目录下,打包时候打包到EXE根目录下即可。
"build": {
"productName": "machine-electron-project",
"appId": "com.example.yourapp",
"extraResources": {
"from": "./config.json",
"to": "../"
}
}
当然如果你想把配置文件放在其他地方也是可以的,在vue中使用 fs.readFile也能读取到,比如config.json文件在d盘下,你可以把文件路径写成'd:\config.json'
let file = 'd:\\config.json' // 文件路径
fs.readFile(file, 'utf-8', function (err, data) {
if (err) {
console.log(err)// eslint-disable-line
} else {
console.log(data)// eslint-disable-line
}
})
评论(2)
1
你的文章被垃圾CSDN盗用,并设置为VIP付费文章。 https://blog.csdn.net/weixin_39681161/article/details/111532660