You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

122 lines
2.1KB

  1. const {app} = require('electron');
  2. const fs = require('fs');
  3. const path = require('path');
  4. function normalizePath(filepath){
  5. let breakIndex = filepath.indexOf("://");
  6. if (breakIndex > 0){
  7. let basepath = app.getPath('home');
  8. let type = filepath.substring(0, breakIndex).toLowerCase()
  9. filepath = filepath.substring(breakIndex + 3, filepath.length - 1);
  10. switch(type){
  11. case "app":
  12. basepath = app.getAppPath();
  13. break;
  14. case "home":
  15. basepath = path.join(basepath, '.saam');
  16. break;
  17. case "user":
  18. basepath = app.getPath('userData');
  19. }
  20. return path.join(basepath, filepath);
  21. }
  22. return filepath;
  23. }
  24. function readFile(file, encoding = null){
  25. return new Promise((res, rej) => {
  26. fs.readFile(file, encoding, (err, data) => {
  27. if (err){rej(err);}
  28. res(data);
  29. });
  30. });
  31. }
  32. function writeFile(file, data){
  33. return new Promise((res, rej) => {
  34. fs.writeFile(file, data, (err) => {
  35. if (err){rej(err);}
  36. res();
  37. });
  38. });
  39. }
  40. async function load(filepath){
  41. filepath = normalizePath(filepath);
  42. try{
  43. return await readFile(filepath);
  44. } catch (e){
  45. throw e;
  46. }
  47. }
  48. async function loadJSON(filepath){
  49. filepath = normalizePath(filepath);
  50. let res = null;
  51. try {
  52. res = await readFile(filepath, 'utf8');
  53. } catch (e) {
  54. console.log("WARNING: Failed to load file '", filepath, "'. ", e.toString());
  55. }
  56. if (res !== null){
  57. try{
  58. return JSON.parse(res);
  59. } catch (e) {
  60. console.log("WARNING: Malformed data at ", filepath);
  61. }
  62. }
  63. return {};
  64. }
  65. async function save(filepath, data){
  66. filepath = normalizePath(filepath);
  67. try {
  68. await writeFile(filepath, data);
  69. } catch (err){
  70. throw err;
  71. }
  72. }
  73. async function saveJSON(filepath, data){
  74. if (typeof data !== 'object')
  75. throw new Error("Expected a data Object.");
  76. let jdat = "";
  77. try{
  78. jdat = JSON.stringify(data);
  79. } catch (e) {
  80. throw new Error("Failed to convert data to JSON string.");
  81. }
  82. try {
  83. await save(filepath, jdat);
  84. } catch (err){
  85. throw err;
  86. }
  87. }
  88. const SFS = {
  89. load,
  90. save,
  91. loadJSON,
  92. saveJSON
  93. };
  94. module.exports = SFS;