当我需要让电子读取本地文件时,我有一个电子项目。
现在我所拥有的是这个,它加载并显示 html 文件的内容。
我现在只需要它来读取文件并将其存储在变量中。
这是我当前的 main.js:
const {app, BrowserWindow } = require('electron');
const path = require('path');
const url = require('url');
var fs = require('fs');
let mainWindow;
function createNewWindow() {
mainWindow = new BrowserWindow({
width: 1300,
height: 1000,
minWidth: 600,
minHeight: 400,
title: 'Test App'
})
}
function loadInitialUrl() {
mainWindow.loadURL(url.format({
pathname: path.join(__dirname, 'index.html'),
protocol: 'file:',
slashes: true
}))
}
function closeApplication() {
mainWindow.on('closed', () => {
mainWindow = null;
})
}
app.on('ready', function(){
createNewWindow();
loadInitialUrl();
mainWindow.setMenu(null);
mainWindow.openDevTools();
fs.readFile('./README.md', 'utf8', function (err,data) {
if (err) {
return console.log(err);
}
console.log(data);
});
mainWindow.on('closed', function() {mainWindow = null;});
});
我该如何执行此操作,因为它没有在 console.log 中显示 README.md 文件的内容
基本上你需要做以下几件事。
1.加载所需依赖项
var remote = require('remote'); // Load remote compnent that contains the dialog dependency
var dialog = remote.require('dialog'); // Load the dialogs component of the OS
var fs = require('fs'); // Load the File System to execute our common tasks (CRUD)
2.读取文件内容
dialog.showOpenDialog((fileNames) => {
// fileNames is an array that contains all the selected
if(fileNames === undefined){
console.log("No file selected");
return;
}
fs.readFile(filepath, 'utf-8', (err, data) => {
if(err){
alert("An error ocurred reading the file :" + err.message);
return;
}
// Change how to handle the file content
console.log("The file content is : " + data);
});
});
3.更新现有文件内容
var filepath = "C:/Previous-filepath/existinfile.txt";// you need to save the filepath when you open the file to update without use the filechooser dialog againg
var content = "This is the new content of the file";
fs.writeFile(filepath, content, (err) => {
if (err) {
alert("An error ocurred updating the file" + err.message);
console.log(err);
return;
}
alert("The file has been succesfully saved");
});
欲了解更多内容,请访问此处:)谢谢..
还要添加一件事..请检查您的文件路径是否正确。你可以做类似下面的事情。
var path = require('path');
var p = path.join(__dirname, '.', 'README.md');
仅提供已接受答案的一项更新信息。 Electron更新后就可以直接使用了
const { dialog } = require('electron');
导入对话框。
而对于远程,如果需要使用,还需要:
const { remote } = require('electron');
从 Electron 20 开始,之前的答案不再正确。
这需要使用进程间连接器 (IPC) 代码从有权访问
fs
和 require
的主进程进行中继。
这就像一个发布-订阅系统,其中主进程有一个密钥监听器,例如:
// main.js
const { app, BrowserWindow, ipcMain } = require('electron')
const path = require('node:path')
const fs = require('fs')
const createWindow = () => {
const win = new BrowserWindow({
width: 1400,
height: 1000,
webPreferences: {
preload: path.join(__dirname, 'preload.js')
}
})
win.loadFile('index.html')
}
app.whenReady().then(() => {
// The event listener
ipcMain.handle('readFile', async (event) => {
return fs.readFileSync(path.join(__dirname, 'README.md'), 'utf-8')
})
你的 preload.js 包含加载文件的触发器:
// preload.js
const { ipcRenderer } = require('electron')
// Note: This is a good place to put your Electron-only client-side JS code.
const loadFile = async filepath => {
// Invoking the event
const contents = await ipcRenderer.invoke('readFile', filepath)
// Do whatever you want with the contents here
})
loadFile()
注意:如果您需要先加载 DOM,则在以下位置运行 loadFile 可能是有意义的:
window.addEventListener('DOMContentLoaded', () => {
loadFile()
})