Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit b37cba8

Browse files
NodeJS Week 2 homework is done.
1 parent f1c3800 commit b37cba8

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
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+
};

0 commit comments

Comments
 (0)