我正在制作我的第一个电子应用程序。我试图将一个文本文件保存到appData文件夹(例如C:\Users\user\AppData\Roaming
)。我知道我需要在某个地方添加import { app } from "electron";
,但我不确定该放在哪里。
在我的index.js
javascript中,我将用户在表单中提交的数据库设置写入一个文本文件,这是我需要appData
目录地址的地方。
// Write data to text file
var filepath = app.getPath("appData")
var filename = "database_quick_image_forensics.txt"
var inp_data = inp_host + "|" + inp_username + "|" + inp_password + "|" + inp_database_name + "|" + inp_table_prefix;
write_to_file(filepath, filename, inp_data);
我的整个代码如下:./setup/index.html
:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Setup</title>
<!-- https://electronjs.org/docs/tutorial/security#csp-meta-tag -->
<!-- CSS -->
<link rel="stylesheet" type="text/css" href="../_webdesign/dark/dark.css" />
<!-- // CSS -->
<!-- jQuery -->
<script>window.$ = window.jQuery = require('../javascripts/jquery/jquery-3.4.1.js');</script>
<script src="../javascripts/jquery/jquery-3.4.1.js" charset="utf-8"></script>
<!-- //jQuery -->
<!-- jQuery -->
<script src="./index.js" charset="utf-8"></script>
<!-- //jQuery -->
</head>
<body>
<div id="main_single_column">
<h1>Setup</h1>
<!-- Feedback -->
<div id="feedback_div" class="success">
<p id="feedback_p">Success</p>
</div>
<!-- //Feedback -->
<!-- Database connection form -->
<p>Host:<br />
<input type="text" name="inp_host" id="inp_host" value="localhost" />
</p>
<p>Port:<br />
<input type="text" name="inpport" id="inp_port" value="" />
</p>
<p>Username:<br />
<input type="text" name="inp_username" id="inp_username" value="root" />
</p>
<p>Password:<br />
<input type="text" name="inp_password" id="inp_password" />
</p>
<p>Database name:<br />
<input type="text" name="inp_database_name" id="inp_database_name" value="quick" />
</p>
<p>Table prefix:<br />
<input type="text" name="inp_table_prefix" id="inp_table_prefix" value="cf_" />
</p>
<p>
<button id="form_connect_to_database_submit">Connect to database</button>
</p>
<!-- //Database connection form -->
</div>
</body>
</html>
./setup/index.js
:
const fs = require('fs');
// Action = On submit
$(document).ready(function(){
$("#form_connect_to_database_submit").click( function() {
// Feedback
$('#feedback_div').show();
$('#feedback_div').removeClass("success");
$('#feedback_div').addClass("info");
$('#feedback_p').text("Connecting!")
// get all the inputs
var inp_host = $("#inp_host"). val();
var inp_username = $("#inp_username"). val();
var inp_password = $("#inp_password"). val();
var inp_database_name = $("#inp_database_name"). val();
var inp_table_prefix = $("#inp_table_prefix"). val();
// Test connection
var connection_result = connect_to_database(inp_host, inp_username, inp_password, inp_database_name, inp_table_prefix);
if(connection_result != "connection_ok"){
// Connection Failed
$('#feedback_div').removeClass("info");
$('#feedback_div').addClass("error");
$('#feedback_p').text(connection_result)
}
else{
// Connection OK
$('#feedback_div').removeClass("info");
$('#feedback_div').addClass("success");
$('#feedback_p').text("Connected")
// Write data to text file
var filepath = app.getPath("appData")
var filename = "database_quick_image_forensics.txt"
var inp_data = inp_host + "|" + inp_username + "|" + inp_password + "|" + inp_database_name + "|" + inp_table_prefix;
$('#feedback_p').text("Connected " + filepath)
write_to_file(filepath, filename, inp_data);
// Feedback
$('#feedback_div').removeClass("info");
$('#feedback_div').addClass("success");
$('#feedback_p').text("Connected to")
}
});
$('#inp_host').focus();
});
// Function connect to database
function connect_to_database(inp_host, inp_username, inp_password, inp_database_name, inp_table_prefix){
var mysql = require('mysql');
// Add the credentials to access your database
var connection = mysql.createConnection({
host : inp_host,
user : inp_username,
password : null, // or the original password : 'apaswword'
database : inp_database_name
});
// connect to mysql
connection.connect(function(err) {
// in case of error
if(err){
console.log(err.code);
console.log(err.fatal);
return err.code;
}
});
// Perform a query
$query = 'SELECT * FROM `cf_admin_liquidbase` LIMIT 10';
connection.query($query, function(err, rows, fields) {
if(err){
console.log("An error ocurred performing the query.");
console.log(err);
return;
}
console.log("Query succesfully executed", rows);
});
return "connection_ok";
} // connect_to_database
// Function write setup
function write_to_file(filepath, filename, inp_data){
var fullpath = filepath + "\\" + filename;
fs.writeFile(fullpath, inp_data, (err) => {
// throws an error, you could also catch it here
if (err) throw err;
// success case, the file was saved
console.log('Lyric saved!');
});
} // write_to_file
./main.js
:
const { app, BrowserWindow } = require('electron')
// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let win
function createWindow () {
// Create the browser window.
win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true
}
})
// and load the index.html of the app.
win.loadFile('index.html')
// Open the DevTools.
// win.webContents.openDevTools()
// Emitted when the window is closed.
win.on('closed', () => {
// Dereference the window object, usually you would store windows
// in an array if your app supports multi windows, this is the time
// when you should delete the corresponding element.
win = null
})
}
// 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', createWindow)
// 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 (win === null) {
createWindow()
}
})
// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.
2条答案
按热度按时间ehxuflar1#
我知道我需要从“electronic”添加import { app };有些地方,但我不知道该把它放在哪里。
根据我的经验,app模块总是导入到
main
进程中,这样您就可以控制应用程序的生命周期。但是,如果您想在renderer
进程中使用一些app
模块功能,您可以通过remote
模块将其导入到那里(如此问题的公认答案所示:如何使用electronic的app.getPath()来存储数据?)main
和renderer
进程是Electron
中的关键概念,所以我建议你仔细阅读它们。要点是你有一个main
进程--它没有可视化的表示形式,它与应用的生命周期有关,创建和销毁renderer
进程(如BrowserWindows)、渲染器进程之间的通信等-而且您可以根据需要拥有任意多个renderer
进程。所以如果你想读写文件,你可以在
renderer
进程中完成,如上所示-或者你可以在main
进程中完成,在后一种情况下,如果一个renderer
进程想保存一个文件,它可以通过IPC发送消息给main
进程,发送要保存的数据。采用哪种方式是一种体系结构选择。
sbtkgmzw2#
获取主进程中的应用程序路径。然后在main.js中使用此代码
从渲染器获取路径,然后在渲染器中使用此代码
但是要在渲染器中使用require,请确保nodeintegration为真。
如果我是你,我会在主进程获取应用路径,并将文件存储在主进程。因此,在渲染器进程导入许多依赖项不是一个好选择。渲染器进程主要负责在Chromium浏览器中显示应用。
因此,要在主进程处执行此操作,请使用
在您的main.js
在渲染器进程中添加以下代码。
正如您所看到的,在渲染器进程中,它通过'WRITE_TEXT'IPC通道将
inp_data
发送到您的主进程。还有一件事,在这里,在你的代码。你正在连接你的数据库在你的渲染器,这是可能的,但这不是一个正确的选择。请思考,而你有几个渲染器。你应该把它移到主进程了。