Не могу сохранить / создать файлы с помощью Store.js - PullRequest
0 голосов
/ 28 марта 2019

Итак, я хотел сохранить файл в хранилище клиента с помощью 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

Но все 3 из них не работали.

Это мой 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: по какой-то причине у меня это не работает (я получаю странные ошибки, которые они не хотят исправлять ..).

Если у кого-то есть идея, то, пожалуйста, я буду благодарен.

1 Ответ

0 голосов
/ 28 марта 2019

Итак, мне удалось решить проблему: почему fs посылает мне ошибки о неопределенных функциях? Почему файл не создается? Он НИЧЕГО не имеет отношения к самому коду, но импортирует ...

Чтобы уточнить, я использовал:

const fs = require('fs');

И решение состоит в том, чтобы сделать это как:

const fs = window.require('fs');

Просто добавление window. устранило все проблемы. Так как я впервые использую электрон, я не привык импортировать из window, но, похоже, это необходимо. это исправить.

...