Electron Dialog的使用以及打开目录、文件以及读写配
2022-11-20 本文已影响0人
扶得一人醉如苏沐晨
需求:在Electron中我期望打开某个目录,修改其目录下的某个配置文件
要打开目录、或者文件,就需要用到Electron的dialog。
该Api只支持再主程序使用,其他程序要使用就需要跟着下面步骤走。
第一步,引入:@electron/remote 新版取消了remote
npm install --save @electron/remote
第二步,再主程序中使用它。
1.引入remote模块
const remote = require("@electron/remote/main");
2.启用remote模块,渲染进程就可以使用主程序模块
remote.enable(win.webContents);
完整background.js代码
"use strict";
import { app, protocol, BrowserWindow } from "electron";
import { createProtocol } from "vue-cli-plugin-electron-builder/lib";
import installExtension, { VUEJS_DEVTOOLS } from "electron-devtools-installer";
const isDevelopment = process.env.NODE_ENV !== "production";
const path = require("path");
// *************************1.引入remote模块******************************
const remote = require("@electron/remote/main");
remote.initialize();
// Scheme must be registered before the app is ready
protocol.registerSchemesAsPrivileged([
{ scheme: "app", privileges: { secure: true, standard: true } },
]);
async function createWindow() {
// Create the browser window.
const win = new BrowserWindow({
// 初始窗口
width: 1200,
height: 900,
// 全屏
// fullscreen: true,
autoHideMenuBar: true, //隐藏菜单
icon: "./icon.ico",
webPreferences: {
nodeIntegration: true, // 使渲染进程拥有node环境
//关闭web权限检查,允许跨域
webSecurity: false,
// Use pluginOptions.nodeIntegration, leave this alone
// See nklayman.github.io/vue-cli-plugin-electron-builder/guide/security.html#node-integration for more info
nodeIntegration: process.env.ELECTRON_NODE_INTEGRATION,
contextIsolation: !process.env.ELECTRON_NODE_INTEGRATION,
},
});
// ********2.启用remote模块,渲染进程就可以使用主程序模块********************
remote.enable(win.webContents);
if (process.env.WEBPACK_DEV_SERVER_URL) {
// Load the url of the dev server if in development mode
await win.loadURL(process.env.WEBPACK_DEV_SERVER_URL);
if (!process.env.IS_TEST) win.webContents.openDevTools();
} else {
createProtocol("app");
// Load the index.html when not in development
win.loadURL("app://./index.html");
}
}
// Quit when all windows are closed.
app.on("window-all-closed", () => {
// On macOS it is common for applications and their menu bar
// to stay active until the user quits explicitly with Cmd + Q
if (process.platform !== "darwin") {
app.quit();
}
});
app.on("activate", () => {
// On macOS it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (BrowserWindow.getAllWindows().length === 0) createWindow();
});
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on("ready", async () => {
if (isDevelopment && !process.env.IS_TEST) {
// Install Vue Devtools
try {
await installExtension(VUEJS_DEVTOOLS);
} catch (e) {
console.error("Vue Devtools failed to install:", e.toString());
}
}
createWindow();
});
// Exit cleanly on request from parent process in development mode.
if (isDevelopment) {
if (process.platform === "win32") {
process.on("message", (data) => {
if (data === "graceful-exit") {
app.quit();
}
});
} else {
process.on("SIGTERM", () => {
app.quit();
});
}
}
完成以上两个步揍后,我就可以在其他窗口使用dialog了。
话不多说,直接先上HTML代码:
<el-form :model="form" label-width="120px">
<el-form-item label="请选择你的文件:">
<el-input v-model="filePath" placeholder="请选择你的文件" readonly @click="selectDirectory"/>
</el-form-item>
</el-form>
<el-row>
<el-button @click="readFile">读取配置文件</el-button>
<el-button @click="writeFile">写入配置文件</el-button>
</el-row>
引入
const { dialog } = require('@electron/remote')
console.log(dialog, 'dialog')
//引入node原生fs模块
const fs = require("fs")
//引入node原生读写配置
const ini = require('ini');
数据源data中
data() {
return {
filePath: "",
config:null,
}
},
methods中
methods: {
selectDirectory() {
dialog.showOpenDialog({
properties: ["openFile"] // 选择文件
// properties: ["openDirectory"] // 选择目录
}).then((results) => {
// console.log(results.filePaths);
// console.log(results.canceled);
this.filePath = results.filePaths[0];
})
},
// 读取配置文件
readFile(){
if(!this.filePath){
this.errMsg("请先选择文件")
return
}
this.config = ini.parse(fs.readFileSync(this.filePath).toString());
console.log(this.config,'config')
},
// 写配置文件
writeFile(){
if(!this.config){
this.errMsg("请先读取文件")
return
}
this.config.xxxxx = "你想要修改的值"
fs.writeFileSync(this.filePath, ini.stringify(this.config))
},
errMsg(msg){
dialog.showErrorBox("错误信息",msg);
},
}