当我需要让电子读取本地文件时,我有一个电子项目。
现在我拥有的是它,它加载并显示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文件的内容
答案 0 :(得分:8)
基本上你需要做以下事情。
1.Loading required dependencies
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");
});
如需更多阅读,请访问here :)谢谢..
还有一件事要添加..请检查您的文件路径是否正确。你可以做类似于下面的事情。
var path = require('path');
var p = path.join(__dirname, '.', 'README.md');
答案 1 :(得分:0)
仅一个更新信息即可接受该答案。电子更新后,可以直接使用
const { dialog } = require('electron');
导入对话框。
对于远程,如果需要使用它,则还需要:
const { remote } = require('electron');