上一篇 electron 编写 hello world
下一篇 electron主进程和渲染进程
任务: 在electron渲染进程中使用node的fs模块读取数据,并显示在网页上
文件结构
learn_electron/
├── package.json
├── main.js
├── index.html
├── loader.js
└── data.txt
编写代码
main.js
const { app, BrowserWindow } = require('electron');
let mainWindow = null;
app.on('ready', () => {
mainWindow = new BrowserWindow({
width: 800,
height: 800,
// 在渲染进程中使用node, 需要要配置webPreferences属性
webPreferences: {nodeIntegration: true}
});
mainWindow.loadFile('index.html'); // 加载网页
mainWindow.on('close', () => {
mainWindow = null;
})
})
index.html
<button id="btn">加载数据</button>
<h2 id="my-data"></h2>
<script src="loader.js"></script>
loader.js
// 引入fs模块
const fs = require('fs');
window.onload = function () {
const btn = document.querySelector("#btn");
const myData = document.querySelector("#my-data");
btn.onclick = function () {
// 读取data.txt文件
fs.readFile("data.txt", (err, data) => {
// 写入网页
myData.innerHTML = data;
})
}
}
data.txt
我是很多很多数据。。
运行结果

欢迎 点赞/评论/关注

网友评论