|
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121 |
-
- 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;
-
-
-
-
-
-
-
|