如何获取预加载的 AppData 目录?
背景.js
[...]
async function createWindow() {
const win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
preload: path.join(__static, "preload.js"),
nodeIntegration: process.env.ELECTRON_NODE_INTEGRATION,
contextIsolation: !process.env.ELECTRON_NODE_INTEGRATION
},
})
}
[...]
preload.js
const { contextBridge } = require('electron')
contextBridge.exposeInMainWorld(
'configManager',
require("../src/utils/config-manager")
)
config-manager.js
const app = require("electron").app
const fs = require("fs")
const resourcePath = app.getPath('appData').replaceAll("\\", "/") + "my-custom-path" // <---
const configPath = resourcePath + "config.json"
const defaultConfig = [ ... ]
let config;
function createFilesIfNotExists(){
if (!fs.existsSync(resourcePath))
fs.mkdirSync(resourcePath)
if (!fs.existsSync(configPath)){
fs.writeFileSync(configPath, JSON.stringify(defaultConfig, null, 4))
return true
}
return false
}
module.exports = {
loadConfig() {
createFilesIfNotExists()
[...]
return config
}
}
如果我运行这个,我会收到此错误。
TypeError: Cannot read property 'getPath' of undefined
at Object. (VM77 config-manager.js:3)
at Object. (VM77 config-manager.js:65)
at Module._compile (VM43 loader.js:1078)
at Object.Module._extensions..js (VM43 loader.js:1108)
at Module.load (VM43 loader.js:935)
at Module._load (VM43 loader.js:776)
at Function.f._load (VM70 asar_bundle.js:5)
at Function.o._load (VM75 renderer_init.js:33)
at Module.require (VM43 loader.js:959)
at require (VM50 helpers.js:88)
(anonymous) @ VM75 renderer_init.js:93
我认为发生这种情况是因为“app”稍后初始化。
我的最终目标是从 AppData 目录中读取 json 配置。
如果有更好的方法来做到这一点,请随时告诉我。
用户不必能够在运行时更改配置。但我必须能够将 defaultConfig 中的默认值写入配置文件中。
Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号