File tree 1 file changed +37
-0
lines changed
week2/homework/src/utility
1 file changed +37
-0
lines changed Original file line number Diff line number Diff line change
1
+ "use strict" ;
2
+
3
+ const fs = require ( "fs" ) ;
4
+
5
+ const utilityAdd = title => {
6
+ let todos = [ ] ;
7
+ let todo = {
8
+ title
9
+ } ;
10
+
11
+ //Try to read the json file:
12
+
13
+ try {
14
+ let todosString = fs . readFileSync ( "./todolist.json" ) ;
15
+ todos = JSON . parse ( todosString ) ;
16
+ } catch ( err ) { }
17
+
18
+ //Check if there is any data inside the json file:
19
+ if ( todos . length === 0 ) {
20
+ // If there is no data, just push the user input:
21
+ todos . push ( todo ) ;
22
+ fs . writeFileSync ( "./todolist.json" , JSON . stringify ( todos ) ) ;
23
+ } else {
24
+ // If there is data inside the json file, read it first.
25
+ let writtenJson = fs . readFileSync ( "./todolist.json" ) ;
26
+ // Then parse it & store it inside the todos array.
27
+ todos = JSON . parse ( writtenJson ) ;
28
+ // Push the current input to that array.
29
+ todos . push ( todo ) ;
30
+ // Write back the updated data in json format to the file:
31
+ fs . writeFileSync ( "./todolist.json" , JSON . stringify ( todos ) ) ;
32
+ }
33
+ } ;
34
+
35
+ module . exports = {
36
+ utilityAdd
37
+ } ;
You can’t perform that action at this time.
0 commit comments