所以我想使用 Store.js 在客户端存储上保存一个文件。
我可以使用store.set
更改日期,并且可以将其log
控制台以查看更改,但是它应该保存在未创建的应用程序数据中。
我试图获取保存它的路径,它是:
C:UsersUSERAppDataRoamingstoma2/Categories.json
我注意到有一个"/",所以我尝试:
C:UsersUSERAppDataRoamingstoma2Categories.json
和: C:/Users/USER/AppData/Roaming/stoma2/Categories.json
但是他们三个都没有工作。
这是我的商店.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;
可能存在问题 fith 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 向我发送有关未定义函数的错误?为什么没有创建文件?它与它本身的代码无关,但导入...
为了澄清,我使用了:
const fs = require('fs');
解决方案是让它像:
const fs = window.require('fs');
只需添加window.
就可以解决所有问题。由于这是我第一次使用电子,我不习惯从window
导入,但似乎有必要。还有更多...没有帖子说这是修复程序。