【发布时间】:2019-08-18 13:49:04
【问题描述】:
所以我想使用 Store.js 在客户端存储中保存一个文件。
我可以使用store.set 更改日期,我可以log 将其发送到控制台以查看更改,但它应该保存在未创建的应用数据中。
我试图获取它被保存的路径,它是:
C:\Users\USER\AppData\Roaming\stoma2/Categories.json
我注意到有一个“/”所以我尝试了:
C:\Users\USER\AppData\Roaming\stoma2\Categories.json
和 :
C:/Users/USER/AppData/Roaming/stoma2/Categories.json
但是这三个都没有用。
这是我的 Store.js:
const fs = require('browserify-fs');
var fs2 = require('filereader'),Fs2 = new fs2();
const electron = window.require('electron');
const path = require('path');
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');
var userDataPath = (electron.app || electron.remote.app).getPath('userData');
for(var i=0;i<userDataPath.length;i++){
if(userDataPath.charAt(i)=="\\"){
userDataPath = userDataPath.replace("\\","/");
}
}
// 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);
console.log(this.path);
}
// This will just return the property on the `data` object
get(key) {
return this.data[key];
}
// ...and this will set it
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.writeFile(this.path, JSON.stringify(this.data));
}
}
function parseDataFile(filePath, data) {
// 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(Fs2.readAsDataURL(new File(filePath)));
} catch(error) {
// if there was some kind of error, return the passed in defaults instead.
return data;
}
}
// expose the class
export default Store;
js.writeFile() 可能有问题(这就是问题的根源)。
这是我的电话:
//creation
const storeDefCat = new Store({
configName: "Categories",
defaults: require("../data/DefaultCategorie.json")
})
//call for the save
storeDefCat.set('Pizza',{id:0,path:storeDefCat.get('Pizza').path});
如果可能的话,现在我可能需要找到另一种方法来保存文件。
我试过了:fs:由于某种原因它对我不起作用(我得到了他们不想修复的奇怪错误..)。
如果有人有想法,我将不胜感激。
【问题讨论】:
-
您在不理解代码的情况下剪切和粘贴代码。阅读我昨天再次发布的教程链接。
-
不是不理解,当我用普通的 fs api 尝试它时,我得到了关于函数不存在的奇怪错误,所以我使用
browserify-fs来解决错误,但这似乎并没有解决问题。 (TypeError: fs.writeFileSync 不是函数)
标签: javascript reactjs save electron store