如何獲取在桌面上運行的電子應用程式的用戶檔案檔案夾路徑。我嘗試了以下方法,但得到一個錯誤app is undefined。
import fs from "fs";
const { app } = require("electron");
export function getFilepath() {
const filepath = app.getPath("userData") "/settings.json";
return filepath;
}
此代碼位于通過我的electron_preload.js檔案匯入的helpers.js檔案中。
我不知道什么或如何解決這個問題。
import { contextBridge, ipcRenderer } from "electron";
const helpers= require("../src/helpers");
contextBridge.exposeInMainWorld("helpers", helpers);
uj5u.com熱心網友回復:
由于您在預加載環境中執行代碼,因此它正在相應的渲染器行程中運行BrowserWindow。但是,app僅限于主行程的執行范圍(source),這就是您的代碼引發錯誤的原因。
您必須通過 IPC 公開路徑。
// Main process, app.js or whatever
const { ipcMain, app } = require ("electron");
ipcMain.handle ("get-user-data-path", (event, ...args) => {
return app.getPath ("userData") "/settings.json";
});
// In helpers.js
import fs from "fs";
const { ipcRenderer } = require("electron");
export async function getFilepath () {
return await ipcRenderer.invoke ("get-user-data-path");
}
更深入的解釋見官方Electron IPC 教程。
(附帶說明:檔案系統的 I/O 可能應該由主行程完成,而不是渲染器。從安全的角度來看值得考慮。)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/437180.html
