所以我想使用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:由于某种原因,它对我不起作用(我收到奇怪的错误,表示它们不希望得到解决。)。
如果有人有一个想法,那么我将不胜感激。
答案 0 :(得分:0)
所以我设法解决了问题,为什么fs向我发送有关未定义函数的错误?为什么没有创建文件?它与自己的代码无关,但是导入...
为了澄清,我使用的是:
const fs = require('fs');
解决方案是使它像:
const fs = window.require('fs');
仅添加window.
就解决了所有问题。由于这是我第一次使用电子,因此我不习惯从window
导入电子,但这似乎是有必要的。没有帖子说这是解决方法。