电子应用将数据存储到系统时会崩溃(用代码3221225477退出的应用程序)
我正在使用电子应用程序,并且正在使用以下类实现来保存和检索用户磁盘的数据。但是,有时此功能正确,有时该程序会崩溃并输出此错误。
用代码3221225477退出的应用程序
我不太确定是什么原因导致了此问题。我了解此错误代码意味着发生了违反访问的情况,但是我不确定为什么会发生访问。可能是班级的实施。我只是从这里拿出实施
也有没有随机发生这种情况,因此可能不是商店实现。
const electron = require('electron');
const path = require('path');
const fs = require('fs');
class Store {
constructor(opts) {
// Renderer process has to get `app` module via `remote`, whereas the main process can get it directly
// app.getPath('userData') will return a string of the user's app data directory path.
const userDataPath = (electron.app || electron.remote.app).getPath('userData');
// We'll use the `configName` property to set the file name and path.join to bring it all together as a string
this.path = path.join(userDataPath, opts.configName + '.json');
this.data = parseDataFile(this.path, opts.defaults);
}
// This will just return the property on the `data` object
get(key) {
const val = this.data[key];
console.log('Get', key, val);
return val;
}
// ...and this will set it
set(key, val) {
console.log('Set', key, val)
this.data[key] = val;
// Wait, I thought using the node.js' synchronous APIs was bad form?
// We're not writing a server so there's not nearly the same IO demand on the process
// Also if we used an async API and our app was quit before the asynchronous write had a chance to complete,
// we might lose that data. Note that in a real app, we would try/catch this.
fs.writeFileSync(this.path, JSON.stringify(this.data));
}
}
function parseDataFile(filePath, defaults) {
// We'll try/catch it in case the file doesn't exist yet, which will be the case on the first application run.
// `fs.readFileSync` will return a JSON string which we then parse into a Javascript object
try {
return JSON.parse(fs.readFileSync(filePath));
} catch(error) {
// if there was some kind of error, return the passed in defaults instead.
return defaults;
}
}
// expose the class
module.exports = Store;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我似乎发现了这个问题的原因。以下帖子包含评论,说
https://stackoverflow.com/a/59796326/7259551
简单地使BrowserWindow的实例仅使BrowserWindow的实例修复了这个问题。
I seem to have discovered the reason for this issue. The following post contains a comment which says
https://stackoverflow.com/a/59796326/7259551
Simply making the instance of BrowserWindow a global value fixed this issue.