-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnotes.js
86 lines (76 loc) · 2.12 KB
/
notes.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
const fs = require("fs");
// Adding a new Note to notes.json file
const addNote = function (title, body) {
const notes = loadNotes();
const createdDate = new Date().toLocaleString();
const duplicateNote = notes.filter(function (note) {
return note.title === title;
});
if (duplicateNote.length === 0) {
notes.push({
title: title,
body: body,
date: createdDate,
});
saveNote(notes);
console.log("Notes added succesfully!");
} else console.log("Notes title already exist!");
};
//Load all notes available in notes.json
const loadNotes = function () {
try {
const dataFetch = fs.readFileSync("notes.json");
const dataFetchToString = dataFetch.toString();
return JSON.parse(dataFetchToString);
} catch (ex) {
return [];
}
};
//Save new notes to notes.json file
const saveNote = function (notes) {
const dataJSON = JSON.stringify(notes);
fs.writeFileSync("notes.json", dataJSON);
};
//Remove a note from notes.json file
const removeNote = function (title) {
const notes = loadNotes();
const keepNotes = notes.filter(function (note) {
return note.title !== title;
});
if (notes.length > keepNotes.length) {
saveNote(keepNotes);
console.log("Note " + title + " removed succesfully!");
} else console.log("Note not found!");
};
// List all notes available in notes.json file
const listNotes = () => {
const dataFetch = loadNotes();
console.log("Your Notes Title");
dataFetch.forEach((note) => {
return console.log(note.title);
});
};
//Read a note from notes.json file
const readNote = (title) => {
const dataFetch = loadNotes();
// const dataToRead = dataFetch.filter(note => {
// if (note.title === title) {
// return console.log(note.body);
// }
// });
const dataToRead = dataFetch.find((note) => {
return note.title === title;
});
if (dataToRead) {
console.log("Title: " + dataToRead.title);
console.log("Body: " + dataToRead.body);
} else {
console.log("Title not found!");
}
};
module.exports = {
addNote: addNote,
removeNote: removeNote,
listNotes: listNotes,
readNote: readNote,
};