@@ -16,7 +16,7 @@ const os = require( 'os' );
1616// A default settings.json object.
1717const defaultObj = { "windowSize" :"1920x1080" , "fullscreen" :false , "language" :"en" ,
1818 "path" : storage . getDefaultDataPath ( ) + path . sep + "data" ,
19- "currency" :"Euro" , "chartType" :"pie" } ;
19+ "currency" :"Euro" , "chartType" :"pie" , "backup" : false , "backupFail" : false } ;
2020// A default mainStorage.json object.
2121const defaultStorageObj = { "budgets" :[ [ "checking account" , 0.0 ] ] , "currentDate" :getCurrentDate ( ) ,
2222 "allTimeEarnings" :[ [ "checking account" , 0.0 ] ] ,
@@ -32,6 +32,7 @@ var currentFile = readPreference( "path" ) + path.sep + getCurrentFileName();
3232module . exports . readPreference = ( name ) => readPreference ( name ) ;
3333module . exports . storePreference = ( name , value ) => storePreference ( name , value ) ;
3434module . exports . initStorage = ( ) => initStorage ( ) ;
35+ module . exports . createBackup = ( ) => createBackup ( ) ;
3536
3637/**
3738 * This function initializes the storage. This means, we create a mainStorage.json
@@ -594,4 +595,30 @@ function readJSONFile( filename ) {
594595function writePDF ( pdfPath , data ) {
595596 pdfPath = pdfPath [ 0 ] + path . sep + selectedMonth + ".pdf" ;
596597 fs . writeFileSync ( pdfPath , data ) ;
598+ }
599+
600+ /**
601+ * Creates a backup of the data.
602+ */
603+ function createBackup ( ) {
604+ var allFiles = fs . readdirSync ( readPreference ( "path" ) ) ;
605+ // Iterate over all the files and create a copy of them.
606+ for ( var i = 0 ; i < allFiles . length ; i ++ ) {
607+ if ( allFiles [ i ] . endsWith ( ".json" ) ) {
608+ try { // (Cross disk will cause an error)
609+ var data = fs . readFileSync ( readPreference ( "path" ) + path . sep + allFiles [ i ] ) ;
610+ // Only write if file is new or it was changed.
611+ if ( fs . existsSync ( readPreference ( "backupPath" ) + path . sep + allFiles [ i ] ) ) {
612+ if ( ! Buffer . from ( data ) . equals ( fs . readFileSync ( readPreference ( "backupPath" ) + path . sep + allFiles [ i ] ) ) ) {
613+ fs . writeFileSync ( readPreference ( "backupPath" ) + path . sep + allFiles [ i ] , data ) ;
614+ }
615+ } else {
616+ fs . writeFileSync ( readPreference ( "backupPath" ) + path . sep + allFiles [ i ] , data ) ;
617+ }
618+ } catch ( err ) {
619+ storePreference ( "backupFail" , true ) ;
620+ break ;
621+ }
622+ }
623+ }
597624}
0 commit comments