文章目录
后端node读取本地文件给前端显示
1 目标
后端node读取本地文件前端显示。
2 步骤
2.1 src-electron/main.js
通过 Electron 的 ipcMain 和 ipcRenderer 进行通信,主进程可以接收渲染进程的请求,并通过fs 读取文件内容。
/*
* @Author: alan.lau
* @Date: 2024-09-08 20:35:17
* @LastEditTime: 2024-09-08 21:49:51
* @LastEditors: alan.lau
* @Description:
* @FilePath: \electron-demo\src-electron\main.js
* 可以输入预定的版权声明、个性签名、空行等
*/
const { app, BrowserWindow, ipcMain } = require("electron");
const { join } = require("path");
const fs = require("fs");
const path = require("path");
// 屏蔽安全警告
process.env["ELECTRON_DISABLE_SECURITY_WARNINGS"] = "true";
// 创建浏览器窗口时,调用这个函数。
const createWindow = () => {
const win = new BrowserWindow({
width: 800,
height: 600,
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,
preload: path.join(__dirname, "preload.js"), // 这里是预加载脚本的位置
},
});
// win.loadURL('http://localhost:3000')
// development模式
if (process.env.VITE_DEV_SERVER_URL) {
win.loadURL(process.env.VITE_DEV_SERVER_URL);
// 开启调试台
win.webContents.openDevTools();
} else {
win.loadFile(join(__dirname, "../dist/index.html"));
}
};
// Electron 会在初始化后并准备
app.whenReady().then(() => {
createWindow();
app.on("activate", () => {
if (BrowserWindow.getAllWindows().length === 0) createWindow();
});
});
app.on("window-all-closed", () => {
if (process.platform !== "darwin") app.quit();
});
// 监听从渲染进程发来的 'read-file' 请求,并读取文件
ipcMain.handle('read-file', async (event, filePath) => {
try {
const data = fs.readFileSync(filePath, 'utf-8');
return data; // 返回文件内容
} catch (error) {
console.error('读取文件失败:', error);
return null;
}
});
2.2 src-electron/preload.js
创建 preload.js,确保在 preload.js 中暴露 ipcRenderer 以供前端使用:
const { contextBridge, ipcRenderer } = require("electron");
contextBridge.exposeInMainWorld("electronAPI", {
readFile: (filePath) => ipcRenderer.invoke("read-file", filePath),
});
2.3 HelloWorld.vue
在Vue 组件中,通过window.electronAPI.readFile 来读取文件
<!--
* @Author: alan.lau
* @Date: 2024-09-08 20:04:38
* @LastEditTime: 2024-09-08 21:16:59
* @LastEditors: alan.lau
* @Description:
* @FilePath: \electron-demo\src\components\HelloWorld.vue
* 可以输入预定的版权声明、个性签名、空行等
-->
<script setup lang="ts">
import { ref, onMounted } from "vue";
import * as Cesium from 'cesium';
defineProps<{ msg: string }>()
const count = ref(0)
var viewer: Cesium.Viewer | null = null;
onMounted(() => {
viewer = new Cesium.Viewer('cesiumContainer', {
terrain: Cesium.Terrain.fromWorldTerrain(), // 地形数据
});
});
const handleReadFileFromNode = async () => {
const content = await window.electronAPI.readFile('D:\\work\\111.txt'); // 读取文件内容
console.log(content)
};
</script>
<template>
<h1>{{ msg }}</h1>
<el-button type="primary" @click="handleReadFileFromNode">我是 ElButton</el-button>
<el-container class="home-container">
<el-header>
</el-header>
<el-main>
<div id="cesiumContainer">
</div>
</el-main>
</el-container>
</template>
<style scoped>
.read-the-docs {
color: #888;
}
</style>
2.4 运行工程
npm run dev
看到一下界面说明成功