|
-
- const {app} = require('electron');
- const fs = require('fs');
- const path = require('path');
-
-
- function normalizePath(filepath){
- let breakIndex = filepath.indexOf("://");
- if (breakIndex > 0){
- let basepath = app.getPath('home');
- let type = filepath.substring(0, breakIndex).toLowerCase()
- filepath = filepath.substring(breakIndex + 3, filepath.length - 1);
-
- switch(type){
- case "app":
- basepath = app.getAppPath();
- break;
- case "home":
- basepath = path.join(basepath, '.saam');
- break;
- case "user":
- basepath = app.getPath('userData');
- }
- return path.join(basepath, filepath);
- }
- return filepath;
- }
-
- function readFile(file, encoding = null){
- return new Promise((res, rej) => {
- fs.readFile(file, encoding, (err, data) => {
- if (err){rej(err);}
- res(data);
- });
- });
- }
-
- function writeFile(file, data){
- return new Promise((res, rej) => {
- fs.writeFile(file, data, (err) => {
- if (err){rej(err);}
- res();
- });
- });
- }
-
-
- async function load(filepath){
- filepath = normalizePath(filepath);
- try{
- return await readFile(filepath);
- } catch (e){
- throw e;
- }
- }
-
-
- async function loadJSON(filepath){
- filepath = normalizePath(filepath);
- let res = null;
- try {
- res = await readFile(filepath, 'utf8');
- } catch (e) {
- console.log("WARNING: Failed to load file '", filepath, "'. ", e.toString());
- }
- if (res !== null){
- try{
- return JSON.parse(res);
- } catch (e) {
- console.log("WARNING: Malformed data at ", filepath);
- }
- }
- return {};
- }
-
-
- async function save(filepath, data){
- filepath = normalizePath(filepath);
- try {
- await writeFile(filepath, data);
- } catch (err){
- throw err;
- }
- }
-
-
- async function saveJSON(filepath, data){
- if (typeof data !== 'object')
- throw new Error("Expected a data Object.");
-
- let jdat = "";
- try{
- jdat = JSON.stringify(data);
- } catch (e) {
- throw new Error("Failed to convert data to JSON string.");
- }
-
- try {
- await save(filepath, jdat);
- } catch (err){
- throw err;
- }
- }
-
-
- const SFS = {
- load,
- save,
- loadJSON,
- saveJSON
- };
-
-
- module.exports = SFS;
-
-
-
-
-
-
|